requireJS(['constant', 'site', 'handlebars'], function (Constant, site, Handlebars) {

    Constant.initHandlebars(Handlebars);

    var product_id = getAurlparam('product_id');
    var order_id = getAurlparam('order_id');
    var taskId = getAurlparam('task_id');
    var node_id = getAurlparam('node_id');
    var s_id = getAurlparam('s_id');
    var personalId;
    var last_node_id;

    //用来存储已存在客户的选择
    var arr = [];

    //表单验证中，弹框focus事件移除error样式
    $("input").on('focus', function () {
        $(this).removeClass('error');
    });

    //表单验证中，弹框focus事件移除error样式
    function removeError() {
        $("input").on('focus', function () {
            $(this).removeClass('error');
        });

        $("select").on("change", function () {
            $(this).removeClass('error');
        })
    }

    //激活datepicker
    function initDatePicker() {
        $(".datepicker").datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            pickerPosition: 'bottom',
        })
    }

    initDatePicker();

    //激活性别的选择事件
    function initSexPicker() {
        $('.sex-radio').on('click', function () {
            $(this).siblings('.sex-radio').removeClass('is-checked');
            $(this).addClass('is-checked');
        })
    }

    initSexPicker();

    //删除事件
    function deletePerson() {
        $('.del').on('click', function () {
            $(this).parents('tr').remove();
        })
    }

    var flag = 0;
    var url = {

        /***************自定义表单部分接口****************/
        insertOrder: "manager/insertOrderPublicNew.do",
        updateOrderInfoAll: "manager/updateOrderInfoAllNew.do",
        queryAdminRoleByRole: "manager/queryAdminRoleByRoleId.do",
        roamTask: "manager/roamTask.do",
        queryProductForm: "manager/selectProductFormCustom.do",
        queryOrderAndProduct: "manager/queryOrderInfos.do",
        getOrderNumber: "manager/getOrderNumber.do",
        selectLoanTypeList: "manager/selectLoanTypeList.do",
        selectApplyTermList: "manager/selectApplyTermList.do",
        selectOrderSourceList: "manager/selectOrderSourceList.do",
        selectRepanymentWayList: "manager/selectRepanymentWayList.do",
        //selectLoanMethodList: "manager/selectLoanMethodList.do",
        selectLoanMethodList: "manager/queryLoanDefineByProductId.do",
        //queryFeeDefine: "manager/queryFeeDefineByProductId.do",
        selectInfoByCard: "manager/selectInfoByCard.do",
        queryFeeRelation: "manager/queryFeeRelationByProductId.do",

        ajaxqueryRegion: "manager/ajaxqueryRegion.do",

        /***************客户信息自定义表单部分接口****************/
        selectBorrowers: "manager/selectBorrowers.do",
        selectEducation: "manager/selectEducation.do",
        insertPersonal: "manager/insertPersonalInfo.do",
        selectPersonalList: "manager/selectPersonalList.do",
        selectMarry: "manager/selectMarry.do",

        /***************order_image_upload部分接口****************/

        getSignature: "manager/getSignature.do",
        selectAttachmentType: "manager/selectAttachmentTypeproduct.do",
        insertAttachment: "manager/insertAttachment.do",
        selectAttachmentList: "manager/selectAttachmentAll.do",
        delAttachment: "manager/delAttachment.do",

        /***************流程节点自定义表单***********************/

        queryEndNodeId: "manager/queryEndNodeId.do",
        queryNodeFromInfoAllByONid: "manager/queryNodeFromInfoAllByONid.do",
        saveNodefromInfos: "manager/saveNodefromInfos.do"
    };

    //省市区联动
    site.send({
        url: url.ajaxqueryRegion,
        data: {
            parentId: 0
        },
        callback: function (data) {
            data = JSON.parse(data);
            var source = $("#province_list_tpl").html();
            var template = Handlebars.compile(source);
            var list = data
            var html = template(list)
            $('#province_list').append(html)
            $('#rprovince_list').append(html)
        }
    })

    $("#province_list").on("change", function () {
        if (!$(this).val()) {
            $("#city_list").html('<option value="" selected="selected">选择市</option>');
            $("#area_list").html('<option value="" selected="selected">选择区县</option>');
        }
        else {
            site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: $(this).val()
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#city_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#city_list').html(html)
                }
            })
        }
    })

    $("#city_list").on("change", function () {
        if (!$(this).val()) {
            $("#area_list").html('<option value="" selected="selected">选择区县</option>');
        } else {
            site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: $(this).val()
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#area_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#area_list').html(html)
                }
            })
        }
    })


    $("#rprovince_list").on("change", function () {
        if (!$(this).val()) {
            $("#rcity_list").html('<option value="" selected="selected">选择市</option>');
            $("#rarea_list").html('<option value="" selected="selected">选择区县</option>');
        }
        else {
            site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: $(this).val()
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#rcity_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#rcity_list').html(html)
                }
            })
        }
    })

    $("#rcity_list").on("change", function () {
        if (!$(this).val()) {
            $("#rarea_list").html('<option value="" selected="selected">选择区县</option>');
        } else {
            site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: $(this).val()
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#rarea_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#rarea_list').html(html)
                }
            })
        }
    })

    site.send({
        url: url.selectAttachmentType,
        data: {
            productId: product_id,
            nodeId: node_id
        },
        callback: function (data) {
            data = JSON.parse(data);
            if (data.type == 1) {
                var source = $("#attachmentType_tpl").html();
                var template = Handlebars.compile(source);
                var list = data.content;
                var html = template(list);
                $('#attachmentType').append(html);

                $("#attachmentType").on("change", function () {
                    if (data.content[$(this).val()]) {
                        var remarks = data.content[$(this).val()].remarks ? data.content[$(this).val()].remarks : "";
                        if (remarks) {
                            $(".description").html("附件描述：" + remarks);
                        }
                        else {
                            $(".description").html("");
                        }
                    }
                    else {
                        $(".description").html("");
                    }
                })

            }
        }
    })


    /************客户自定义    order_apply_PersonMess  部分********/
    //身份证失去焦点触发事件
    function addBlur() {
        $('.idCard').off('blur');
        $(".idCard").on('blur', function () {
            var _this = this;
            if ($(_this).val()) {
                var m = $(_this).val()
                if (Constant.reg.isCarid.test(m)) {
                    var n = m.substring(6, 10) + "-" + m.substring(10, 12) + "-" + m.substring(12, 14);
                    $(this).parents('td').find(".birthDate").val(n).change();
                }
                var otherIdCard = $(_this).parents('tr').siblings('tr').find('.idCard');
                for (var i = 0; i < otherIdCard.length; i++) {
                    if ($(_this).val() == $(otherIdCard[i]).val()) {
                        Constant.fn.Message('I', '请勿输入相同的身份证号码')
                        return;
                    }
                }
                site.send({
                    url: url.selectInfoByCard,
                    data: {
                        idCard: $(this).val()
                    },
                    callback: function (data) {
                        data = JSON.parse(data);
                        if (data.type == 1) {
                            if (data.content) {
                                Constant.fn.Message('I', '输入的身份证的号码已存在');
                                personalId = data.content.personalId;
                                $(_this).parents('td').find('.realName').val(data.content.realName);
                                $(_this).parents('td').find('.birthDate').val(data.content.birthDate).change();
                                $(_this).parents('td').find('.cellphone ').val(data.content.cellphone);
                                $(_this).parents('td').find('input[value=' + data.content.sex + ']').parent('.sex-radio').addClass('is-checked');
                            }
                            else {
                                Constant.fn.Message('T', data.msg);
                            }
                        }
                        else {
                            Constant.fn.Message('I', data.msg);
                        }
                    },
                    callError: function (err) {

                    }
                })
            }
        })
    }

    addBlur();

    /*查询已存在客户*/

    var pageNum = 1;

    function queryPerson() {
        var frontData = {
            pageNum: pageNum
        }
        if ($("#seleNames option:selected").val()) {
            frontData.type = $("#seleNames option:selected").val()
        }
        if ($("#inputNames").val()) {
            frontData.keyword = $("#inputNames").val();
        }
        site.send({
            url: url.selectPersonalList,
            data: frontData,
            callback: function (data) {
                data = JSON.parse(data);

                var source = $("#person_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = data.content.list;
                var html = template(list);
                $('#person_list').html(html);
                $('.person_winBox').show();


                $('input[name="896"]').on('click', function () {
                    var _this = this
                    if ($(_this).is(':checked')) {
                        arr.push($(_this).val())
                    } else {
                        $.each(arr, function (i, e) {
                            if (e == $(_this).val()) {
                                arr.splice(i, 1);
                            }
                        })
                    }
                })

                $.each(arr, function (i, e) {
                    $('.person_winBox input[value=' + e + ']').prop('checked', true);
                })

                //winBox弹窗，按钮点击事件
                $(document).on('click', '.icon-wrong.headerIcon', function () {
                    $(this).parents('.person_winBox').hide();
                    $("#seleNames").val('');
                    $("#inputNames").val('');
                })


                if (data.type == 1) {
                    $('.person-page-container').createPager({
                        current: frontData.pageNum,
                        total: data.content.total,
                        pageSize: data.content.pageSize,
                        needInput: false,
                        backFn: function (current) {
                            pageNum = current;
                            queryPerson();
                        }
                    })
                }

                else {
                    Constant.fn.Message('F', data.msg);
                }
            }
        })
    }

    $('.confirm').on('click', function () {
        var _this = this;
        if (arr.length) {
            var borrId = arr.join(',')
            //arr = arr.substr(0, arr.length - 1);
            site.send({
                url: url.selectBorrowers,
                data: {
                    borrId: borrId,
                    product_id: product_id,
                    type: '1'
                },
                callback: function (data) {
                    $(_this).parents('.person_winBox').hide();
                    $("#seleNames").val('');
                    $("#inputNames").val('');
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        personalId = data.content.personalId;
                        if (data.content.boList) {
                            $(".personMess:gt(0)").remove();
                            var boList = data.content.boList;
                            $.each(boList, function (i, e) {
                                var a = i + 1;
                                if (i == 0) {
                                    $(".personMess:first .realName").attr('id', e.id).val(e.realName);
                                    $(".personMess:first .idCard").val(e.idCard);
                                    $(".personMess:first .birthDate").val(e.birthDate);
                                    $(".personMess:first .cellphone").val(e.cellphone);
                                    $('.sex-radio').removeClass('is-checked');
                                    $(".personMess:first input[value=" + e.sex + "]").parent('.sex-radio').addClass('is-checked');
                                }
                                else {
                                    $(".personMess:last").after('<tr i="' + i + '" class="personMess ng-scope">\n' +
                                        '            <td class="ng-binding"><span>*</span>借款人' + a + '</td>\n' +
                                        '            <td colspan="7" style="text-align: left">\n' +
                                        '                <span class="pad">\n' +
                                        '                    <input type="text" placeholder="请输入借款人' + a + '" ng-model="item.realName" id="' + e.id + '" value="' + e.realName + '" class="realName ng-pristine ng-untouched ng-valid ng-empty">\n' +
                                        '                </span>\n' +
                                        '                <span class="pad">\n' +
                                        '                    <input placeholder="输入身份证号码" ng-class="{\'error\':_err.borrTis[$index].idCard}" value="' + e.idCard + '" ng-focus="remFocus()" type="text" style="width:220px" ng-model="item.idCard" ng-blur="getIdCard(key)" class="idCard ng-pristine ng-untouched ng-valid ng-empty">\n' +
                                        '                </span>\n' +
                                        '                <label class="labelinput pad" ng-class="{\'error\':_err.borrTis[$index].birthDate}">\n' +
                                        '                    <input placeholder="请选择生日" value="' + e.birthDate + '" type="text"  class="birthDate datepicker bothDate1 ng-empty">\n' +
                                        '                    <span>\n' +
                                        '                        <i class="iconfont icon-riqi"></i>\n' +
                                        '                    </span>\n' +
                                        '                </label>\n' +
                                        '                <span class="pad">\n' +
                                        '                    <input ng-class="{\'error\':_err.borrTis[$index].cellphone}" ng-focus="remFocus()" type="text" ng-blur="getPhone(key)"  value="' + e.cellphone + '" placeholder="请输入手机号码" ng-model="item.cellphone" class="cellphone ng-pristine ng-untouched ng-valid ng-empty">\n' +
                                        '                </span>\n' +
                                        '                <span class="pad">\n' +
                                        '                    <label class="sex-radio">\n' +
                                        '                        <input type="radio" name="PersonMessSex_' + i + '" value="1" class="ng-pristine ng-untouched ng-valid ng-empty">男\n' +
                                        '                    </label>\n' +
                                        '                    <label class="sex-radio">\n' +
                                        '                        <input type="radio" name="PersonMessSex_' + i + '" value="2" class="ng-pristine ng-untouched ng-valid ng-empty">女\n' +
                                        '                    </label>\n' +
                                        '                </span>\n' +
                                        '                <span class="del ng-scope">删除</span>\n' +
                                        '                <!-- ngIf: key!==0 -->\n' +
                                        '            </td>\n' +
                                        '        </tr>')
                                    $('tr[i=' + i + '] input[value=' + e.sex + ']').parent('.sex-radio').addClass('is-checked');
                                }
                            })
                        }

                        if (data.content.perInfo) {
                            var perInfo = data.content.perInfo
                            $("#address").val(perInfo.address);
                            $("#birthDate").val(perInfo.birth_date);
                            $("#cellphone").val(perInfo.cellphone);
                            $("#idCard").val(perInfo.id_card);
                            $("#residence").val(perInfo.residence);

                            $("#province_list").val(perInfo.addr_province)

                            site.send({
                                url: url.ajaxqueryRegion,
                                data: {
                                    parentId: perInfo.addr_province
                                },
                                callback: function (data) {
                                    data = JSON.parse(data);
                                    var source = $("#city_list_tpl").html();
                                    var template = Handlebars.compile(source);
                                    var list = data
                                    var html = template(list)
                                    $('#city_list').html(html)
                                    $("#city_list").val(perInfo.addr_city)
                                }
                            })

                            site.send({
                                url: url.ajaxqueryRegion,
                                data: {
                                    parentId: perInfo.addr_city
                                },
                                callback: function (data) {
                                    data = JSON.parse(data);
                                    var source = $("#area_list_tpl").html();
                                    var template = Handlebars.compile(source);
                                    var list = data
                                    var html = template(list)
                                    $('#area_list').html(html)
                                    $("#area_list").val(perInfo.addr_area);
                                }
                            })


                            $("#rprovince_list").val(perInfo.resid_province);
                            site.send({
                                url: url.ajaxqueryRegion,
                                data: {
                                    parentId: perInfo.resid_province
                                },
                                callback: function (data) {
                                    data = JSON.parse(data);
                                    var source = $("#rcity_list_tpl").html();
                                    var template = Handlebars.compile(source);
                                    var list = data
                                    var html = template(list)
                                    $('#rcity_list').html(html)
                                    $("#rcity_list").val(perInfo.resid_city);
                                }
                            })

                            site.send({
                                url: url.ajaxqueryRegion,
                                data: {
                                    parentId: perInfo.resid_city
                                },
                                callback: function (data) {
                                    data = JSON.parse(data);
                                    var source = $("#rarea_list_tpl").html();
                                    var template = Handlebars.compile(source);
                                    var list = data
                                    var html = template(list)
                                    $('#rarea_list').html(html)
                                    $("#rarea_list").val(perInfo.resid_area);
                                }
                            })

                            var addr_p_name = perInfo.addr_p_name ? perInfo.addr_p_name : '';
                            var addr_c_name = perInfo.addr_c_name ? perInfo.addr_c_name : '';
                            var addr_a_name = perInfo.addr_a_name ? perInfo.addr_a_name : '';
                            $(".huArea .huInput").val(addr_p_name + addr_c_name + addr_a_name);

                            var resid_p_name = perInfo.resid_p_name ? perInfo.resid_p_name : '';
                            var resid_c_name = perInfo.resid_c_name ? perInfo.resid_c_name : ''
                            var resid_a_name = perInfo.resid_a_name ? perInfo.resid_a_name : ''

                            $(".homeArea .homeInput").val(resid_p_name + resid_c_name + resid_a_name);


                            $("#payee").val(perInfo.payee ? perInfo.payee : "");
                            $("#account").val(perInfo.account ? perInfo.account : "");
                            $("#bank").val(perInfo.bank ? perInfo.bank : "");
                            $("#house > input[type='radio'][value=" + perInfo.house + "]").prop('checked', true);
                            $("#monthRent").val(perInfo.month_rent ? perInfo.month_rent : "");
                            $("#beginTime").val(perInfo.begin_time ? perInfo.begin_time : "");
                            $("#localTime").val(perInfo.local_time ? perInfo.local_time : "");
                            $("#homephone").val(perInfo.homephone ? perInfo.homephone : "");
                            if (perInfo.education) {
                                $("#education_list > option[value=" + perInfo.education + "]").prop('selected', true);
                            }
                            if (perInfo.marry) {
                                $("#marry_list > option[value=" + perInfo.marry + "]").prop('selected', true);
                            }
                            $("#child").val(perInfo.child ? perInfo.child : "");
                        }

                        var personalRealDatas = data.content.personalRealDatas;

                        if (personalRealDatas) {
                            $.each(personalRealDatas, function (index, item) {
                                var type = item.type
                                /*if(index <= 5){
                                    $('td[define_id='+item.property_id+']').attr('op_id',item.id);
                                    switch(type){
                                        case 'select':
                                            $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                            break;
                                        case 'text':
                                            $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                            break;
                                        case 'radio':
                                            $('td[define_id='+item.property_id+'] input[content_id='+item.content_ids+']').attr('checked',true);
                                            break;
                                    }
                                    /!*if(type == 'select'){
                                        $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                    }
                                    if(type == 'text'){
                                        $('td[define_id='+item.property_id+'] input[type="text"]').val(item.value);
                                    }
                                    if(type == 'radio'){
                                        $('td[define_id='+item.property_id+'] input[content_id='+item.content_ids+']').attr('checked',true);
                                    }*!/
                                }*/
                                $('#apply-PersonMess .component[id=' + item.property_id + ']').attr('op_id', item.id);
                                switch (type) {
                                    case 'form_name':
                                        $('#apply-PersonMess .component legend').val(item.value);
                                        break;
                                    case 'checkbox': {
                                        if (item.content_ids) {
                                            var content_ids = item.content_ids;
                                            content_ids = content_ids.split(',');
                                            $.each(content_ids, function (i, e) {
                                                $('#apply-PersonMess .component[id=' + item.property_id + '] input[content_id=' + e + ']').attr('checked', true);
                                            })
                                        }
                                        break;
                                    }

                                    case 'select':
                                        if (item.content_ids) {
                                            $('#apply-PersonMess .component[id=' + item.property_id + '] option[content_id=' + item.content_ids + ']').attr('selected', true);
                                        }
                                        break;
                                    case 'radio':
                                        if (item.content_ids) {
                                            $('#apply-PersonMess .component[id=' + item.property_id + '] input[content_id=' + item.content_ids + ']').attr('checked', true);
                                        }
                                        break;
                                    case 'text':
                                        $('#apply-PersonMess .component[id=' + item.property_id + '] input[type="text"]').val(item.value);
                                        break;
                                    case 'textarea':
                                        $('#apply-PersonMess .component[id=' + item.property_id + '] textarea').val(item.value);
                                    case 'time':
                                        $('#apply-PersonMess .component[id=' + item.property_id + '] input[type="text"]').val(item.value);
                                }
                            })
                        }


                        /*$('#apply-PersonMess .form_myself').html("");
                        $('#apply-message .form_myself').html("");
                        site.send({
                            url: url.queryProductForm,
                            data: {
                                product_id: product_id
                            },
                            callback: function (data) {
                                data = JSON.parse(data);
                                if (data.type == 1) {
                                    //渲染客户自定义部分
                                    if (data.content.personalPropertyCategorys) {
                                        $.each(data.content.personalPropertyCategorys, function (index, item) {
                                            $('#apply-PersonMess .form_myself').append('<div id="pcategorys'+index+'" style="overflow: hidden;"></div>');
                                            $.each(item.personalPropertyDefines, function (index2, item2) {
                                                $("#pcategorys" + index).append(item2.define_html);
                                            })
                                            /!*if(index == 0){
                                                $('#add_form').before(item.template_html);
                                            }*!/
                                            //else{
                                            //}
                                        })
                                        if (order_id) {
                                            fillFormData(order_id);
                                        }
                                    }

                                    //渲染产品自定义部分
                                    if (data.content.productPropertyCategorys) {
                                        $.each(data.content.productPropertyCategorys, function (index, item) {
                                            $('#apply-message .form_myself').append('<div id="mcategorys'+index+'" style="overflow: hidden;"></div>');
                                            $.each(item.personalPropertyDefines, function (index2, item2) {
                                                $("#mcategorys" + index).append(item2.define_html);
                                            })
                                            /!*if(index == 0){
                                                $('#add_form').before(item.template_html);
                                            }*!/
                                            //else{
                                            //$('#apply-message .form_myself').append("<div style='overflow: hidden;'>" + item.template_html + "</div>");
                                            //}
                                        })
                                        if (order_id) {
                                            fillFormData(order_id);
                                        }
                                    }
                                    if (personalRealDatas) {
                                        $.each(personalRealDatas, function (index, item) {
                                            var type = item.type
                                            /!*if(index <= 5){
                                                $('td[define_id='+item.property_id+']').attr('op_id',item.id);
                                                switch(type){
                                                    case 'select':
                                                        $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                                        break;
                                                    case 'text':
                                                        $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                                        break;
                                                    case 'radio':
                                                        $('td[define_id='+item.property_id+'] input[content_id='+item.content_ids+']').attr('checked',true);
                                                        break;
                                                }
                                                /!*if(type == 'select'){
                                                    $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                                }
                                                if(type == 'text'){
                                                    $('td[define_id='+item.property_id+'] input[type="text"]').val(item.value);
                                                }
                                                if(type == 'radio'){
                                                    $('td[define_id='+item.property_id+'] input[content_id='+item.content_ids+']').attr('checked',true);
                                                }*!/
                                            }*!/
                                            //else{
                                            $('#apply-PersonMess .component[id=' + item.property_id + ']').attr('op_id', item.id);
                                            switch (type) {
                                                case 'form_name':
                                                    $('#apply-PersonMess .component legend').val(item.value);
                                                    break;
                                                case 'checkbox': {
                                                    if (item.content_ids) {
                                                        var content_ids = item.content_ids;
                                                        content_ids = content_ids.split(',');
                                                        $.each(content_ids, function (i, e) {
                                                            $('#apply-PersonMess .component[id=' + item.property_id + '] input[content_id=' + e + ']').attr('checked', true);
                                                        })
                                                    }
                                                    break;
                                                }

                                                case 'select':
                                                    if (item.content_ids) {
                                                        $('#apply-PersonMess .component[id=' + item.property_id + '] option[content_id=' + item.content_ids + ']').attr('selected', true);
                                                    }
                                                    break;
                                                case 'radio':
                                                    if (item.content_ids) {
                                                        $('#apply-PersonMess .component[id=' + item.property_id + '] input[content_id=' + item.content_ids + ']').attr('checked', true);
                                                    }
                                                    break;
                                                case 'text':
                                                    $('#apply-PersonMess .component[id=' + item.property_id + '] input[type="text"]').val(item.value);
                                                    break;
                                                case 'textarea':
                                                    $('#apply-PersonMess .component[id=' + item.property_id + '] textarea').val(item.value);
                                                case 'time':
                                                    $('#apply-message .component[id=' + item.property_id + '] input[type="text"]').val(item.value);
                                            }
                                        })
                                    }


                                    //渲染时间控件
                                    $("[leipiplugins='time']").datepicker({
                                        format: 'yyyy-mm-dd',
                                        autoclose: true,
                                        pickerPosition: 'bottom',
                                    })

                                    removeError();
                                }

                                /!*$.each(data.content.productPropertyCategorys,function(index,Categorys){
                                    //$(".public-content").attr('')
                                    $.each(Categorys.productPropertyDefines,function(index,Defines){
                                        $('[leipiplugins][name='+Defines.name+']').attr('define_id',Defines.define_id);
                                        var that = $('[leipiplugins][name='+Defines.name+']');
                                        $.each(Defines.productPropertyContents,function(index,Contents){
                                            //$('[name='+Contents.name+']').attr('content_id',Contents.content_id);
                                            that.children().eq(index).attr('content_id',Contents.content_id);
                                        })
                                    })
                                })*!/
                                else {
                                    Constant.fn.Message("F", data.msg)
                                }
                            }, callError: function () {

                            }
                        })*/


                        initDatePicker();
                        initSexPicker();
                        deletePerson();
                    }
                }
            })
        } else {
            $('.person_winBox').toggle();
        }
    })

    //搜索功能
    $('.showPerson').on('click', function () {
        queryPerson();
    })

    //获取客户自定义表单真实数据
    function getCustomPersonData(orderProductPropertys) {

        // 拿到下半部分自定義表單
        var customForm = $('#apply-PersonMess .form_myself .component');
        $.each(customForm, function (i, e) {

            var element = $(e).find('[leipiplugins]')
            var type = element.attr('leipiplugins');

            //用来村粗content_id和value
            var content_id = '';
            var value = '';

            if (type == 'radio') {
                $.each($(e).find('[content_id]'), function (ii, ee) {
                    if ($(ee).is(':checked')) {
                        content_id = $(ee).attr('content_id');
                        value = $(ee).val();
                    }
                })
                var obj = {
                    property_id: $(e).attr('id'),
                    content_ids: content_id,
                    value: value,
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
            if (type == 'checkbox') {
                $.each($(e).find('[content_id]'), function (ii, ee) {
                    if ($(ee).is(':checked')) {
                        content_id += $(ee).attr('content_id') + ',';
                        value += $(ee).val() + ',';
                    }
                })
                content_id = content_id.substr(0, content_id.length - 1);
                value = value.substr(0, value.length - 1);
                var obj = {
                    property_id: $(e).attr('id'),
                    content_ids: content_id,
                    value: value,
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj)
            }
            if (type == 'select') {
                $.each($(e).find('[content_id]'), function (ii, ee) {
                    if ($(ee).is(':selected')) {
                        content_id = $(ee).attr('content_id');
                        value = $(ee).val();
                    }
                })
                var obj = {
                    property_id: $(e).attr('id'),
                    content_ids: content_id,
                    value: value,
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
            if (type == 'form_name') {
                var obj = {
                    property_id: $(e).attr('id'),
                    value: $(e).find('.category-title').html(),
                    type: type,
                    required: $(e).attr('require')
                };
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj)
            }
            if (type == 'text') {
                var obj = {
                    property_id: $(e).attr('id'),
                    value: $(e).find('input[type="text"]').val(),
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
            if (type == 'time') {
                var obj = {
                    property_id: $(e).attr('id'),
                    value: $(e).find('input[type="text"]').val(),
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
            if (type == 'textarea') {
                var obj = {
                    property_id: $(e).attr('id'),
                    value: $(e).find('textarea').val(),
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
        })
    }


    //实现智能联想
    var searData = {};  //用来存储地址信息

    var Intelligent_association = {

        creSele: function (obj) {
            var autocomplete = $(obj.el).autocomplete({
                hints: obj.data,
                width: obj.width,
                height: obj.height,
                val: obj.val,
                inputClass: obj.inputClass,
                placeholder: obj.placeholder,
                onSubmit: function (text) {
                    obj.backball(text)
                }
            })
            return autocomplete
        },

        initHuArea: function (idxData) {
            var _this = this;
            var huArea = _this.creSele({						//户口所在地
                el: '.huArea',							//页面上的span节点
                data: '',								//需要搜索的所有数据
                width: 158,
                height: 32,
                val: idxData,									//默认input值
                inputClass: 'huInput',					//把动态生成的input class写进去 以免影响插件原有class
                placeholder: '请输入检索城市名称',
                backball: function (text) {				//用户选择后返回的值
                    searData.huArea = text
                    //console.log(text)
                }
            })
            $('.huInput').bind('keyup keydown', function (e) {		//监听用户敲击键盘时搜索数据
                if (e.which > 32 && e.which < 126) return
                if (/^[\u4e00-\u9fa5]*$/.test($(this).val())) {
                    huArea.hints = _this.getCity()				//赋值数据进插件对象huArea
                }
            })
        },

        initHomeArea: function (idxData) {
            var _this = this
            var homeArea = _this.creSele({
                el: '.homeArea',							//页面上的span节点
                data: '',								//需要搜索的所有数据
                width: 158,
                height: 32,
                val: idxData,							//默认input值
                inputClass: 'homeInput',					//把动态生成的input class写进去 以免影响插件原有class
                placeholder: '请输入检索城市名称',
                backball: function (text) {				//用户选择后返回的值
                    searData.homeArea = text
                }
            })
            $('.homeInput').bind('keyup keydown', function (e) {		//监听用户敲击键盘时搜索数据
                if (e.which > 32 && e.which < 126) return
                if (/^[\u4e00-\u9fa5]*$/.test($(this).val())) {
                    homeArea.hints = _this.getCity()						//赋值数据进插件对象huArea
                }
            })
        },

        /*获取json文件中的城市*/
        getCity: function () {
            var city;
            $.ajax({
                type: 'get',
                url: 'static/cityjson.json',
                async: false,
                success: function (data) {
                    city = data
                }
            })
            return city
        },

        /*获取完json数据后转成id 传给后台*/
        getSearId: function (data) {
            var id, city = this.getCity()
            $.each(city, function (idx, item) {
                if (item.name == data) {
                    id = item.id.split(',')
                    return
                }
            })
            return id
        }
    }

    //初始化智能搜索
    Intelligent_association.initHuArea()
    Intelligent_association.initHomeArea()
    /*var hArea = Intelligent_association.getSearId(searData.huArea);
    var homeArea = Intelligent_association.getSearId(searData.homeArea);*/

    //获取教育程度接口

    site.send({
        url: url.selectEducation,
        callback: function (data) {
            data = JSON.parse(data);
            if (data.type == 1) {
                var source = $("#education_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = data.content
                var html = template(list)
                $('#education_list').append(html)
            }
        }
    })
    //获取婚姻状况
    site.send({
        url: url.selectMarry,
        callback: function (data) {
            data = JSON.parse(data);
            if (data.type == 1) {
                var source = $("#marry_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = data.content
                var html = template(list)
                $('#marry_list').append(html)
            }
        }
    })

    function getPersonalData() {

        /***********获取省市区**************/
        /*var hArea = Intelligent_association.getSearId(searData.huArea);
        var homeArea = Intelligent_association.getSearId(searData.homeArea);*/

        /*if (hArea) { */                                                 //户口所在地
        var residProvince = $("#rprovince_list").val();
        var residCity = $("#rcity_list").val();
        var residArea = $("#rarea_list").val();
        /*}*/
        /*if (homeArea) { */                                              //居住地址
        var addrProvince = $("#province_list").val();
        var addrCity = $("#city_list").val();
        var addrArea = $("#area_list").val();
        /*}*/

        /***********获取省市区**************/





        var borrowers = new Array();

        $.each($('.personMess'), function (i, e) {
            var obj = {
                id: $(e).find(".realName").attr('id') ? $(e).find(".realName").attr('id') : '',
                realName: $(e).find(".realName").val(),
                idCard: $(e).find(".idCard").val(),
                birthDate: $(e).find(".birthDate").val(),
                cellphone: $(e).find(".cellphone").val(),
                sex: $(e).find('.is-checked input[type="radio"]').val()
            }
            borrowers.push(obj);
        })

        //var perInfo = new Array();

        var obj = {
            payee: $("#payee").val(),
            account: $("#account").val(),
            bank: $("#bank").val(),
            residProvince: residProvince,
            residCity: residCity,
            residArea: residArea,
            residence: $('#residence').val(),
            addrProvince: addrProvince,
            addrCity: addrCity,
            addrArea: addrArea,
            address: $("#address").val(),
            house: $("#house > input[type='radio']:checked").val(),
            monthRent: $("#monthRent").val(),
            beginTime: $("#beginTime").val(),
            localTime: $("#localTime").val(),
            homephone: $("#homephone").val(),
            education: $("#education_list > option:selected").val(),
            marry: $("#marry_list > option:selected").val(),
            child: $("#child").val()
        }


        var data = {
            personalId: personalId, //客户ID（导入客户 才有）
            borrowers: borrowers,
            perInfo: obj
        }
        return data;
    }


    //表单验证，若验证不通过，则控件添加样式标红


    //点击添加借款人
    $("#addPerson").on('click', function () {
        var i = $('.personMess').length + 1;
        $(".personMess:last").after('<tr class="personMess ng-scope">\n' +
            '            <td class="ng-binding"><span>*</span>借款人' + i + '</td>\n' +
            '            <td colspan="7" style="text-align: left">\n' +
            '                <span class="pad">\n' +
            '                    <input type="text" placeholder="请输入借款人' + i + '" ng-model="item.realName" class="realName ng-pristine ng-untouched ng-valid ng-empty">\n' +
            '                </span>\n' +
            '                <span class="pad">\n' +
            '                    <input placeholder="输入身份证号码" ng-class="{\'error\':_err.borrTis[$index].idCard}" ng-focus="remFocus()" type="text" style="width:220px" ng-model="item.idCard" ng-blur="getIdCard(key)" class="idCard ng-pristine ng-untouched ng-valid ng-empty">\n' +
            '                </span>\n' +
            '                <label class="labelinput pad" ng-class="{\'error\':_err.borrTis[$index].birthDate}">\n' +
            '                    <input placeholder="请选择生日" type="text"  class="birthDate datepicker bothDate1 ng-empty">\n' +
            '                    <span>\n' +
            '                        <i class="iconfont icon-riqi"></i>\n' +
            '                    </span>\n' +
            '                </label>\n' +
            '                <span class="pad">\n' +
            '                    <input ng-class="{\'error\':_err.borrTis[$index].cellphone}" ng-focus="remFocus()" type="text" ng-blur="getPhone(key)" placeholder="请输入手机号码" ng-model="item.cellphone" class="cellphone ng-pristine ng-untouched ng-valid ng-empty">\n' +
            '                </span>\n' +
            '                <span class="pad">\n' +
            '                    <label class="sex-radio">\n' +
            '                        <input type="radio" name="PersonMessSex_' + i + '" value="1" ng-checked="item.sex == 1" ng-model="item.sex" class="ng-pristine ng-untouched ng-valid ng-empty">男\n' +
            '                    </label>\n' +
            '                    <label class="sex-radio">\n' +
            '                        <input type="radio" name="PersonMessSex_' + i + '" value="2" ng-checked="item.sex == 2" ng-model="item.sex" class="ng-pristine ng-untouched ng-valid ng-empty">女\n' +
            '                    </label>\n' +
            '                </span>\n' +
            '                <span class="del ng-scope">删除</span>\n' +
            '                <!-- ngIf: key!==0 -->\n' +
            '            </td>\n' +
            '        </tr>');

        initDatePicker();

        initSexPicker();

        deletePerson();
    })

    /*$('.sex-radio').on('click', function () {
        $('.sex-radio').removeClass('is-checked');
        $(this).addClass('is-checked');
     })*/

    /************客户自定义    order_apply_PersonMess  部分********/


    $('.public-PoBefore-nav li a').on('click', function () {
        var params = $(this).data('type');
        if (params == 'Reimbursement' || params == 'PersonMess' || params == 'message' || params == 'dataList') {
            //Reimbursement=还款明细
            //message=借款信息
            //personMess=借款人資料
            //dataList=資料清單
            //切换菜单
            $('.public-PoBefore-nav li a').removeClass('activePublic');
            $(this).addClass('activePublic');

            //切换内容
            $('.public-content').hide();
            $('#apply-' + params).show();
        }
    });


    /************产品自定义    order_apply_message  部分********/

    $('#apply_money').on({
        'focus': function () {
            $(this).val(Constant.fn.toNum($(this).val()));
        },
        'blur': function () {
            $(this).val(Constant.fn.toRMB($(this).val()));
        }
    })

    function initSelect() {
        site.send({
            url: url.selectLoanTypeList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#loanType_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#loanType_content').html(html);
                }
                else {
                    Constant.fn.Message("F", data.msg);
                }
            }
        })

        site.send({
            url: url.selectApplyTermList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#applyTerm_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#applyTerm_content').html(html);
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectRepanymentWayList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#repanymentWay_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#repanymentWay_content').html(html);
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectOrderSourceList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#orderSource_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#orderSource_content').html(html);
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectLoanMethodList,
            data: {
                product_id: product_id
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#loanMethod_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#loanMethod_content').append(html);
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.queryFeeRelation,
            data: {
                product_id: Constant.getAurlparam('product_id')
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var html = "";
                    $.each(data.content, function (i, e) {
                        var type = e.type == 1 ? '元' : '分';
                        html += '<i fee_id="' + e.fee_id + '"><label class="checkbox inline" type="' + e.type + '"  id="' + e.fee_id + '" style="height: auto; padding:5px 0 0 20px; box-shadow: none"><input type="checkbox"  name="leipiNewField" title="复选框" orginline="inline" style="width: 15px;">' + e.fee_name + '</label><label class="text slabel isDisabled" style="display: block"><input type="text" key="' + e.english_name + '" class="ng-pristine ng-untouched ng-valid ng-empty">' + type + '</label></i>';
                    })
                    $("#count").append(html);

                    //初始化checkbox点击功能
                    $.each($("#count input[type='checkbox']"), function (i, e) {
                        $(e).on('click', function () {
                            var c = $(e).parent('label').siblings('label')
                            if ($(e).is(':checked')) {
                                c.removeClass('isDisabled');
                                c.children('input[type="text"]').show();
                            }
                            else {
                                c.addClass('isDisabled');
                                c.children('input[type="text"]').val('');
                                c.children('input[type="text"]').hide();
                            }
                        })
                    })
                }
            }
        })
    }

    initSelect();

    //初始化上半部分固定表单下拉框

    function initformSelect(content) {
        site.send({
            url: url.selectLoanTypeList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#loanType_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#loanType_content').html(html);

                    var orderInfos = content.orderInfos;
                    $.each(orderInfos, function (i, e) {
                        if (e.fixed_key == "lt_id") {
                            if (e.is_edit == 1) {
                                $("#loanType_content option[data-id=" + e.real_data + "]").attr("selected", true)
                            }
                            else {
                                $("#loanType_content").parents('td').html($("#loanType_content option[data-id=" + e.real_data + "]").text());
                            }
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectApplyTermList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#applyTerm_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#applyTerm_content').html(html);

                    var orderInfos = content.orderInfos;
                    $.each(orderInfos, function (i, e) {
                        if (e.fixed_key == "at_id") {
                            if (e.is_edit == 1) {
                                $("#applyTerm_content option[data-id=" + e.real_data + "]").attr("selected", true)
                            }
                            else {
                                $("#applyTerm_content").parents('td').html($("#applyTerm_content option[data-id=" + e.real_data + "]").text());
                            }
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectRepanymentWayList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#repanymentWay_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#repanymentWay_content').html(html);

                    var orderInfos = content.orderInfos;
                    $.each(orderInfos, function (i, e) {
                        if (e.fixed_key == "repayment_way") {
                            if (e.is_edit == 1) {
                                $("#repanymentWay_content option[data-id=" + e.real_data + "]").attr("selected", true)
                            }
                            else {
                                var real_data = $("#repanymentWay_content option[data-id=" + e.real_data + "]").text()
                                real_data ? $("#repanymentWay_content").parents('td').html(real_data) : "未填写";
                            }
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectOrderSourceList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#orderSource_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#orderSource_content').html(html);

                    var orderInfos = content.orderInfos;
                    $.each(orderInfos, function (i, e) {
                        if (e.fixed_key == "os_id") {
                            if (e.edit == 1) {
                                $("#orderSource_content option[data-id=" + e.real_data + "]").attr("selected", true)
                            }
                            else {
                                var real_data = $("#orderSource_content option[data-id=" + e.real_data + "]").text()
                                real_data ? $("#orderSource_content").parents('td').html(real_data) : "未填写";
                            }
                        }
                        if (e.fixed_key == "apply_money") {
                            if (e.edit == 1) {
                                $("#apply_money").val(e.real_data);
                            }
                            else {
                                $("#apply_money").parents('td').html(e.real_data + "元");
                            }
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectLoanMethodList,
            data: {
                product_id: product_id
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#loanMethod_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#loanMethod_content').append(html);

                    var orderInfos = content.orderInfos;
                    $.each(orderInfos, function (i, e) {
                        if (e.fixed_key == "loan_way") {
                            if (e.edit == 1) {
                                $("#loanMethod_content input[value=" + e.real_data + "]").prop("checked", true);
                            }
                            else {
                                $("#loanMethod_content input[value=" + e.real_data + "]").prop("checked", true);
                                $("#loanMethod_content").parents('tr').html($('#loanMethod_content input[type="radio"]:checked').text());
                            }
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })
    }

    /*//获取借款编号
    function getOrderNumber() {
        site.send({
            url: url.getOrderNumber,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    $('.public-content-Po').html(data.content);
                }
                else {
                    Constant.fn.Message("F", data.msg);
                }
            }
        })

    }

    getOrderNumber();*/


    function fillFormData(order_id) {
        site.send({
            url: url.queryOrderAndProduct,
            data: {
                order_id: order_id,
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var orderDatas = data.content.orderDatas;
                    var productRealDatas = data.content.productRealDatas;
                    var feeDatas = data.content.feeDatas;
                    var personalDatas = data.content.personalDatas;
                    var personalRealDatas = data.content.personalRealDatas;
                    var loanMethodDatas = data.content.loanMethodDatas;
                    personalId = personalDatas.id ? personalDatas.id : "";

                    //扣费明细利率真实数据渲染
                    $("#count span input[type='checkbox']").prop('checked', true);
                    $("#count span label").removeClass('isDisabled');
                    $("#count span input[type='text']").val(orderDatas.interest);

                    //固定字段真实数据渲染
                    $("#apply_money").val(orderDatas.apply_money);
                    $('#loanType_content option[data-id=' + orderDatas.lt_id + ']').prop('selected', true);
                    $('#repanymentWay_content option[data-id=' + orderDatas.repayment_way + ']').prop('selected', true);
                    if (orderDatas.at_id) {
                        $('#applyTerm_content option[data-id=' + orderDatas.at_id + ']').prop('selected', true);
                    }
                    if (orderDatas.loandays) {
                        $("#apply_day").val(orderDatas.loandays);
                    }
                    $('#loanMethod_content input[value=' + orderDatas.loan_way + ']').prop('checked', true);
                    $('#orderSource_content option[data-id=' + orderDatas.os_id + ']').prop('selected', true);

                    //还款方式为按天收息的特殊判断
                    if (orderDatas.repayment_way == '4') {
                        $(".applyTrem").hide()
                        $(".applyDay").show();
                    } else {
                        $(".applyTrem").show();
                        $(".applyDay").hide();
                    }

                    $('.public-content-Po').html(orderDatas.loan_number);

                    $.each(productRealDatas, function (index, item) {
                        var type = item.type
                        /*if(index <= 5){
                            $('td[define_id='+item.property_id+']').attr('op_id',item.id);
                            switch(type){
                                case 'select':
                                    $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                    break;
                                case 'text':
                                    $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                    break;
                                case 'radio':
                                    $('td[define_id='+item.property_id+'] input[content_id='+item.content_ids+']').attr('checked',true);
                                    break;
                            }
                            /!*if(type == 'select'){
                                $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                            }
                            if(type == 'text'){
                                $('td[define_id='+item.property_id+'] input[type="text"]').val(item.value);
                            }
                            if(type == 'radio'){
                                $('td[define_id='+item.property_id+'] input[content_id='+item.content_ids+']').attr('checked',true);
                            }*!/
                        }*/
                        $('#apply-message .component[id=' + item.property_id + ']').attr('op_id', item.id);
                        switch (type) {
                            case 'form_name':
                                $('#apply-message .component legend').val(item.value);
                                break;
                            case 'checkbox': {
                                if (item.content_ids) {
                                    var content_ids = item.content_ids;
                                    content_ids = content_ids.split(',');
                                    $.each(content_ids, function (i, e) {
                                        $('#apply-message .component[id=' + item.property_id + '] input[content_id=' + e + ']').attr('checked', true);
                                    })
                                }
                                break;
                            }

                            case 'select': {
                                if (item.content_ids) {
                                    $('#apply-message .component[id=' + item.property_id + '] option[content_id=' + item.content_ids + ']').attr('selected', true);
                                }
                            }
                                break;
                            case 'radio': {
                                if (item.content_ids) {
                                    $('#apply-message .component[id=' + item.property_id + '] input[content_id=' + item.content_ids + ']').attr('checked', true);
                                }
                            }
                                break;
                            case 'text':
                                $('#apply-message .component[id=' + item.property_id + '] input[type="text"]').val(item.value);
                                break;
                            case 'textarea':
                                $('#apply-message .component[id=' + item.property_id + '] textarea').val(item.value);
                            case 'time':
                                $('#apply-message .component[id=' + item.property_id + '] input[type="text"]').val(item.value);
                        }

                    })

                    //客户固定字段渲染
                    $.each(personalDatas.borrowerDatas, function (i, e) {
                        var a = i + 1;
                        if (i == 0) {
                            $(".personMess:first .realName").attr('id', e.id).val(e.real_name);
                            $(".personMess:first .idCard").val(e.id_card);
                            $(".personMess:first .birthDate").val(e.birth_date);
                            $(".personMess:first .cellphone").val(e.cellphone);
                            $('.sex-radio').removeClass('is-checked');
                            $(".personMess:first input[value=" + e.sex + "]").parent('.sex-radio').addClass('is-checked');
                        }
                        else {
                            $(".personMess:last").after('<tr i="' + i + '" class="personMess ng-scope">\n' +
                                '            <td class="ng-binding"><span>*</span>借款人' + a + '</td>\n' +
                                '            <td colspan="7" style="text-align: left">\n' +
                                '                <span class="pad">\n' +
                                '                    <input type="text" placeholder="请输入借款人' + a + '" ng-model="item.realName" id="' + e.id + '" value="' + e.real_name + '" class="realName ng-pristine ng-untouched ng-valid ng-empty">\n' +
                                '                </span>\n' +
                                '                <span class="pad">\n' +
                                '                    <input placeholder="输入身份证号码" ng-class="{\'error\':_err.borrTis[$index].idCard}" value="' + e.id_card + '" ng-focus="remFocus()" type="text" style="width:220px" ng-model="item.idCard" ng-blur="getIdCard(key)" class="idCard ng-pristine ng-untouched ng-valid ng-empty">\n' +
                                '                </span>\n' +
                                '                <label class="labelinput pad" ng-class="{\'error\':_err.borrTis[$index].birthDate}">\n' +
                                '                    <input placeholder="请选择生日" value="' + e.birth_date + '" type="text"  class="birthDate datepicker bothDate1 ng-empty">\n' +
                                '                    <span>\n' +
                                '                        <i class="iconfont icon-riqi"></i>\n' +
                                '                    </span>\n' +
                                '                </label>\n' +
                                '                <span class="pad">\n' +
                                '                    <input ng-class="{\'error\':_err.borrTis[$index].cellphone}" ng-focus="remFocus()" type="text" ng-blur="getPhone(key)"  value="' + e.cellphone + '" placeholder="请输入手机号码" ng-model="item.cellphone" class="cellphone ng-pristine ng-untouched ng-valid ng-empty">\n' +
                                '                </span>\n' +
                                '                <span class="pad">\n' +
                                '                    <label class="sex-radio">\n' +
                                '                        <input type="radio" name="PersonMessSex_' + i + '" value="1" class="ng-pristine ng-untouched ng-valid ng-empty">男\n' +
                                '                    </label>\n' +
                                '                    <label class="sex-radio">\n' +
                                '                        <input type="radio" name="PersonMessSex_' + i + '" value="2" class="ng-pristine ng-untouched ng-valid ng-empty">女\n' +
                                '                    </label>\n' +
                                '                </span>\n' +
                                '                <span class="del ng-scope">删除</span>\n' +
                                '                <!-- ngIf: key!==0 -->\n' +
                                '            </td>\n' +
                                '        </tr>')
                            $('tr[i=' + i + '] input[value=' + e.sex + ']').parent('.sex-radio').addClass('is-checked');
                        }
                    })

                    initSexPicker();

                    deletePerson();

                    $("#payee").val(personalDatas.payee ? personalDatas.payee : "");
                    $("#account").val(personalDatas.account ? personalDatas.account : "");
                    $("#bank").val(personalDatas.bank ? personalDatas.bank : "");
                    $("#house > input[type='radio'][value=" + personalDatas.house + "]").prop('checked', true);
                    $("#monthRent").val(personalDatas.month_rent ? personalDatas.month_rent : "");
                    $("#beginTime").val(personalDatas.begin_time ? personalDatas.begin_time : "");
                    $("#localTime").val(personalDatas.local_time ? personalDatas.local_time : "");
                    $("#homephone").val(personalDatas.homephone ? personalDatas.homephone : "");
                    if (personalDatas.education) {
                        $("#education_list > option[value=" + personalDatas.education + "]").prop('selected', true);
                    }
                    if (personalDatas.marry) {
                        $("#marry_list > option[value=" + personalDatas.marry + "]").prop('selected', true);
                    }
                    $("#child").val(personalDatas.child ? personalDatas.child : "");


                    $("#address").val(personalDatas.address);
                    $("#residence").val(personalDatas.residence);


                    $("#rprovince_list").val(personalDatas.resid_province)

                    site.send({
                        url: url.ajaxqueryRegion,
                        data: {
                            parentId: personalDatas.resid_province
                        },
                        callback: function (data) {
                            data = JSON.parse(data);
                            var source = $("#rcity_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data
                            var html = template(list)
                            $('#rcity_list').html(html)
                            $("#rcity_list").val(personalDatas.resid_city)
                        }
                    })

                    site.send({
                        url: url.ajaxqueryRegion,
                        data: {
                            parentId: personalDatas.resid_city
                        },
                        callback: function (data) {
                            data = JSON.parse(data);
                            var source = $("#area_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data
                            var html = template(list)
                            $('#rarea_list').html(html)
                            $("#rarea_list").val(personalDatas.resid_area);
                        }
                    })


                    $("#province_list").val(personalDatas.addr_province);
                    site.send({
                        url: url.ajaxqueryRegion,
                        data: {
                            parentId: personalDatas.addr_province
                        },
                        callback: function (data) {
                            data = JSON.parse(data);
                            var source = $("#city_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data
                            var html = template(list)
                            $('#city_list').html(html)
                            $("#city_list").val(personalDatas.addr_city);
                        }
                    })

                    site.send({
                        url: url.ajaxqueryRegion,
                        data: {
                            parentId: personalDatas.addr_city
                        },
                        callback: function (data) {
                            data = JSON.parse(data);
                            var source = $("#area_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data
                            var html = template(list)
                            $('#area_list').html(html)
                            $("#area_list").val(personalDatas.addr_area);
                        }
                    })

                    var addr_p_name = personalDatas.addr_p_name ? personalDatas.addr_p_name : '';
                    var addr_c_name = personalDatas.addr_c_name ? personalDatas.addr_c_name : '';
                    var addr_a_name = personalDatas.addr_a_name ? personalDatas.addr_a_name : '';
                    $(".huArea .huInput").val(addr_p_name + addr_c_name + addr_a_name);
                    searData.huArea = addr_p_name + addr_c_name + addr_a_name;

                    var resid_p_name = personalDatas.resid_p_name ? personalDatas.resid_p_name : '';
                    var resid_c_name = personalDatas.resid_c_name ? personalDatas.resid_c_name : ''
                    var resid_a_name = personalDatas.resid_a_name ? personalDatas.resid_a_name : ''

                    $(".homeArea .homeInput").val(resid_p_name + resid_c_name + resid_a_name);
                    searData.homeArea = resid_p_name + resid_c_name + resid_a_name;

                    $.each(personalRealDatas, function (index, item) {
                        var type = item.type
                        /*if(index <= 5){
                            $('td[define_id='+item.property_id+']').attr('op_id',item.id);
                            switch(type){
                                case 'select':
                                    $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                    break;
                                case 'text':
                                    $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                                    break;
                                case 'radio':
                                    $('td[define_id='+item.property_id+'] input[content_id='+item.content_ids+']').attr('checked',true);
                                    break;
                            }
                            /!*if(type == 'select'){
                                $('td[define_id='+item.property_id+'] option[content_id='+item.content_ids+']').attr('selected',true);
                            }
                            if(type == 'text'){
                                $('td[define_id='+item.property_id+'] input[type="text"]').val(item.value);
                            }
                            if(type == 'radio'){
                                $('td[define_id='+item.property_id+'] input[content_id='+item.content_ids+']').attr('checked',true);
                            }*!/
                        }*/
                        //else{
                        $('#apply-PersonMess .component[id=' + item.property_id + ']').attr('op_id', item.id);
                        switch (type) {
                            case 'form_name':
                                $('#apply-PersonMess .component legend').val(item.value);
                                break;
                            case 'checkbox': {
                                if (item.content_ids) {
                                    var content_ids = item.content_ids;
                                    content_ids = content_ids.split(',');
                                    $.each(content_ids, function (i, e) {
                                        $('#apply-PersonMess .component[id=' + item.property_id + '] input[content_id=' + e + ']').attr('checked', true);
                                    })
                                }
                                break;
                            }

                            case 'select':
                                if (item.content_ids) {
                                    $('#apply-PersonMess .component[id=' + item.property_id + '] option[content_id=' + item.content_ids + ']').attr('selected', true);
                                }
                                break;
                            case 'radio':
                                if (item.content_ids) {
                                    $('#apply-PersonMess .component[id=' + item.property_id + '] input[content_id=' + item.content_ids + ']').attr('checked', true);
                                }
                                break;
                            case 'text':
                                $('#apply-PersonMess .component[id=' + item.property_id + '] input[type="text"]').val(item.value);
                                break;
                            case 'textarea':
                                $('#apply-PersonMess .component[id=' + item.property_id + '] textarea').val(item.value);
                            case 'time':
                                $('#apply-PersonMess .component[id=' + item.property_id + '] input[type="text"]').val(item.value);
                        }
                    })

                    $.each(feeDatas, function (index, item) {
                        $('td i[fee_id=' + item.fee_id + ']').attr('order_fee_id', item.id);
                        $('td i[fee_id=' + item.fee_id + '] input[type="checkbox"]').attr('checked', true);
                        $('td i[fee_id=' + item.fee_id + '] input[type="checkbox"]').parent('label').attr('order_fee_id', item.id);
                        $('td i[fee_id=' + item.fee_id + '] label').removeClass('isDisabled');
                        $('td i[fee_id=' + item.fee_id + '] input[type="text"]').show();
                        $('td i[fee_id=' + item.fee_id + '] input[type="text"]').val(item.fee);
                    })

                    $.each(loanMethodDatas, function (i, e) {
                        $('#loanway input[loan_mehtod_id=' + e.loan_id + ']').prop('checked', true);
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            },
            callError: function () {
                Constant.fn.Message("F", "请求失败")
            }
        });
    }

    //表单验证
    //查询出要固定表单和自定义表单
    function queryForm(order_id) {
        site.send({
            url: url.queryProductForm,
            data: {
                product_id: product_id
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    //渲染客户自定义部分
                    if (data.content.personalPropertyCategorys) {
                        $.each(data.content.personalPropertyCategorys, function (index, item) {
                            $('#apply-PersonMess .form_myself').append('<div id="pcategorys' + index + '" style="overflow: hidden;"></div>');
                            $.each(item.personalPropertyDefines, function (index2, item2) {
                                $("#pcategorys" + index).append(item2.define_html);
                            })
                            /*if(index == 0){
                                $('#add_form').before(item.template_html);
                            }*/
                            //else{
                            // $('#apply-PersonMess .form_myself').append("<div style='overflow: hidden;'>" + item.template_html + "</div>");
                            //}
                        })
                    }

                    //渲染产品自定义部分
                    if (data.content.productPropertyCategorys) {
                        $.each(data.content.productPropertyCategorys, function (index, item) {
                            $('#apply-message .form_myself').append('<div id="mcategorys' + index + '" style="overflow: hidden;"></div>');
                            $.each(item.personalPropertyDefines, function (index2, item2) {
                                $("#mcategorys" + index).append(item2.define_html);
                            })
                            /*if(index == 0){
                                $('#add_form').before(item.template_html);
                            }*/
                            //else{
                            $('#apply-message .form_myself').append("<div style='overflow: hidden;'>" + item.template_html + "</div>");
                            //}
                        })
                    }

                    //渲染时间控件
                    $("[leipiplugins='time']").datepicker({
                        format: 'yyyy-mm-dd',
                        autoclose: true,
                        pickerPosition: 'bottom',
                    })
                    if (order_id) {
                        fillFormData(order_id);
                    }
                }

                /*$.each(data.content.productPropertyCategorys,function(index,Categorys){
                    //$(".public-content").attr('')
                    $.each(Categorys.productPropertyDefines,function(index,Defines){
                        $('[leipiplugins][name='+Defines.name+']').attr('define_id',Defines.define_id);
                        var that = $('[leipiplugins][name='+Defines.name+']');
                        $.each(Defines.productPropertyContents,function(index,Contents){
                            //$('[name='+Contents.name+']').attr('content_id',Contents.content_id);
                            that.children().eq(index).attr('content_id',Contents.content_id);
                        })
                    })
                })*/
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }, callError: function () {

            }
        })
    }

    //监听扣费明细选中框的选中事件

    //先查询出表单
    queryForm(order_id);


    //查询出角色
    function queryRole(order_id) {
        site.send({
            url: url.queryAdminRoleByRole,
            //async:false
            data: {
                order_id: order_id
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    var source = $("#role_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data.content
                    var html = template(list)
                    $('.assBox2').html(html)

                    //下拉框选中获取值
                    $("#role_select").on('change', function () {
                        userId = $(this).find("option:selected").val();
                    })
                }
            }
        })
    }

    //流转查询出表单
    function queryNodeForm(order_id, node_id, product_id) {
        site.send({
            url: url.queryNodeFromInfoAllByONid,
            data: {
                node_id: node_id,
                order_id: order_id,
                product_id: product_id
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    //handlebars模板引擎
                    var source = $("#form_list_tpl").html()
                    var template = Handlebars.compile(source)
                    var content = data.content
                    var html = template(content)
                    $('.formBox').html(html)
                    /*var content = data.content;
                    if(content.productInfos)
                    {
                        $('.formBox').append("<table class=\"resultTab\" style=\"margin: 20px 0px;\"><tbody></tbody></table>")
                        $.each(content.productInfos,function(i,e){
                            if(e.define_type != 'form_name'){
                                $('.resultTab tbody').append('')
                            }
                        })
                    }*/


                    initFormSelect(content);
                    //渲染真实数据

                }
            }
        })
    }

    //流转
    function roamTask(userId, remark) {
        var data = {
            taskId: taskId,
            userId: userId,
            orderId: order_id,
            remark: remark,
            type: '1'
        }
        site.send({
            url: url.roamTask,
            data: data,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    $('.processForm_winBox').toggle();
                    Constant.fn.Message('T', data.msg);
                    //pjaxReload();
                    history.go(-1);
                } else {
                    Constant.fn.Message("F", data.msg)
                }
            },
            callError: function () {

            }
        })
    }

    function saveNodefromInfos() {
        var productInfos = new Array();
        //获取产品自定义真实数据信息
        var td = $(".productInfos").find('td[property_id]');
        $.each(td, function (i, e) {
            var productForm = $(e).find('[productForm]')
            if (productForm.attr('productForm') == 'text') {
                var obj = {
                    property_id: $(e).attr('property_id'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    order_id: order_id,
                    value: productForm.val(),
                    record_value: productForm.val()
                }
            }
            if (productForm.attr('productForm') == 'select') {
                var obj = {
                    property_id: $(e).attr('property_id'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    order_id: order_id,
                    content_ids: productForm.find('option:selected').val(),
                    value: productForm.find('option:selected').val() ? productForm.find('option:selected').text() : '',
                    record_value: productForm.find('option:selected').val() ? productForm.find('option:selected').text() : ''
                }
            }
            if (productForm.attr('productForm') == 'radio') {
                var content_ids = "";
                var value = "";
                var record_value = "";
                $.each(productForm, function (ii, ee) {
                    if ($(ee).is(":checked")) {
                        content_ids = $(ee).val();
                        value = $(ee).parent('label').text();
                        record_value = $(ee).parent('label').text();
                    }
                })
                var obj = {
                    property_id: $(e).attr('property_id'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    order_id: order_id,
                    content_ids: content_ids,
                    value: value,
                    record_value: record_value
                }
            }
            if (productForm.attr('productForm') == 'textarea') {
                var obj = {
                    property_id: $(e).attr('property_id'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    order_id: order_id,
                    value: productForm.val(),
                    record_value: productForm.val()
                }
            }
            if (productForm.attr('productForm') == 'checkbox') {
                var content_ids = "";
                var value = "";
                var record_value = "";
                $.each(productForm, function (ii, ee) {
                    if ($(ee).is(":checked")) {
                        content_ids += $(ee).val() + ',';
                        value += $(ee).parent('label').text() + ',';
                        record_value += $(ee).parent('label').text() + ',';
                    }
                })
                content_ids = content_ids.substring(0, content_ids.length - 1)
                value = value.substring(0, value.length - 1)
                record_value = record_value.substring(0, record_value.length - 1)
                var obj = {
                    property_id: $(e).attr('property_id'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    order_id: order_id,
                    content_ids: content_ids,
                    value: value,
                    record_value: record_value
                }
            }
            //if (obj.required == '1' || obj.value != '') {
            productInfos.push(obj);
            //}
        })


        var productFeeInfos = new Array();

        var charging = $("input[fee_id]");

        $.each(charging, function (i, e) {
            var obj = {
                fee_id: $(e).attr("fee_id"),
                name: $(e).attr('name'),
                fixed_name: $(e).attr('name'),
                required: $(e).attr('require'),
                order_id: order_id,
                fee: $(e).val(),
                record_value: $(e).val()
            }
            productFeeInfos.push(obj);
        })


        var loanInfos = new Array();

        var loan = $("input[loan_id]:checked");
        if (loan.length) {
            loanInfos.push({
                loan_id: loan.attr("loan_id"),
                order_id: order_id,
                required: '1',
                value: loan.parent('label').text(),
                record_value: loan.parent('label').text()
            })
        }

        var orderInfos = new Array();

        var column = $("[column_key]")
        $.each(column, function (i, e) {
            if ($(e).attr('column_key') == 'loan_way') {
                var value = $(e).find('input[type="radio"]:checked').val();
                var obj = {
                    order_id: order_id,
                    column_key: $(e).attr('column_key'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    value: value
                }
            }
            else if ($(e).attr('column_key') == 'apply_money') {
                var obj = {
                    order_id: order_id,
                    column_key: $(e).attr('column_key'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    value: parseInt(Constant.fn.toNum($(e).val()))
                }
            } else if ($(e).attr('column_key') == 'interest') {
                var obj = {
                    order_id: order_id,
                    column_key: $(e).attr('column_key'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    value: $(e).val(),
                    record_value: $(e).val()
                }
            }
            else {
                var option = $(e).find('option:selected');
                var obj = {
                    order_id: order_id,
                    column_key: $(e).attr('column_key'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    value: option.data('id') ? option.data('id') : "",
                    record_value: option.data('id') ? option.text() : ""
                }
            }
            //if (obj.required == '1' || obj.value != '') {
            orderInfos.push(obj);
            //}
        })


        var frontData = {
            productInfos: productInfos,
            productFeeInfos: productFeeInfos,
            orderInfos: orderInfos,
        }

        var productInfos = frontData.productInfos;
        var productFeeInfos = frontData.productFeeInfos;
        var orderInfos = frontData.orderInfos;


        for (var i = 0; i < productInfos.length; i++) {
            if (productInfos[i].required == '1' && !productInfos[i].value) {
                Constant.fn.Message('I', '请填写' + productInfos[i].name);
                return;
            }
        }

        for (var i = 0; i < productFeeInfos.length; i++) {
            if (productFeeInfos[i].required == '1' && !productFeeInfos[i].fee) {
                Constant.fn.Message('I', '请填写' + productFeeInfos[i].name);
                return;
            }
        }

        for (var i = 0; i < orderInfos.length; i++) {
            if (orderInfos[i].required == '1' && !orderInfos[i].value) {
                Constant.fn.Message('I', '请填写' + orderInfos[i].name);
                return;
            }
        }

        /*for (var i = 0; i < loanInfos.length; i++) {
            if (loanInfos[i].required == '1' && !loanInfos[i].value) {
                Constant.fn.Message('I', '请填写贷款方式');
                ;
                return
            }
        }*/

        //验证是否选择角色
        var userId = $("#role_select option:selected").val();
        var remark = $(".approveRemark").val();
        if (last_node_id != node_id) {
            if (!userId) {
                Constant.fn.Message('I', '请选择审批角色');
                return;
            }
        }
        if (!remark) {
            Constant.fn.Message('I', '请输入备注');
            return;
        }
        ;

        site.send({
            url: url.saveNodefromInfos,
            data: {
                frontData: JSON.stringify(frontData)
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    roamTask(userId, remark);
                }
                else {
                    Constant.fn.Message('F', data.msg);
                }
            }
        })
    }

    /*//点击隐藏
    $("#show").on('click', function (e) {
        e.stopPropagation();
        $('.winBox').toggle();
    })*/


    //点击流转
    $("#roamTask").on("click", function (e) {
        e.stopPropagation();
        var remark = $('.approveRemark').val();
        if (!userId) {
            Constant.fn.Message("I", "请选择审批角色");
            return;
        }
        if (!remark) {
            Constant.fn.Message("I", "请输入备注");
            return;
        }
        roamTask(userId, remark);
        //saveNodefromInfos();
    })

    function getCustomProductData(orderProductPropertys) {

        // 拿到下半部分自定義表單
        var customForm = $('#apply-message .form_myself .component');
        $.each(customForm, function (i, e) {

            var element = $(e).find('[leipiplugins]')
            var type = element.attr('leipiplugins');

            //用来村粗content_id和value
            var content_id = '';
            var value = '';

            if (type == 'radio') {
                $.each($(e).find('[content_id]'), function (ii, ee) {
                    if ($(ee).is(':checked')) {
                        content_id = $(ee).attr('content_id');
                        value = $(ee).val();
                    }
                })
                var obj = {
                    property_id: $(e).attr('id'),
                    content_ids: content_id,
                    value: value,
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
            if (type == 'checkbox') {
                $.each($(e).find('[content_id]'), function (ii, ee) {
                    if ($(ee).is(':checked')) {
                        content_id += $(ee).attr('content_id') + ',';
                        value += $(ee).val() + ',';
                    }
                })
                content_id = content_id.substr(0, content_id.length - 1);
                value = value.substr(0, value.length - 1);
                var obj = {
                    property_id: $(e).attr('id'),
                    content_ids: content_id,
                    value: value,
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj)
            }
            if (type == 'select') {
                $.each($(e).find('[content_id]'), function (ii, ee) {
                    if ($(ee).is(':selected')) {
                        content_id = $(ee).attr('content_id');
                        value = content_id ? $(ee).val() : '';
                    }
                })
                var obj = {
                    property_id: $(e).attr('id'),
                    content_ids: content_id,
                    value: value,
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
            if (type == 'form_name') {
                var obj = {
                    property_id: $(e).attr('id'),
                    value: $(e).find('.category-title').html(),
                    type: type,
                    required: $(e).attr('require')
                };
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj)
            }
            if (type == 'text') {
                var obj = {
                    property_id: $(e).attr('id'),
                    value: $(e).find('input[type="text"]').val(),
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
            if (type == 'textarea') {
                var obj = {
                    property_id: $(e).attr('id'),
                    value: $(e).find('textarea').val(),
                    type: type,
                    required: $(e).attr('require')
                }
                if ($(e).attr('op_id')) {
                    obj.op_id = $(e).attr('op_id');
                }
                orderProductPropertys.push(obj);
            }
        })
    }

    $("#repanymentWay_content").on('change', function () {
        if ($(this).find('option:selected').data('id') == '4') {
            $('.applyTrem').hide();
            $('.applyDay').show();
        } else {
            $('.applyTrem').show();
            $('.applyDay').hide();
        }
    })

    //保存并发起
    function saveAdd() {

        var personalData = getPersonalData();

        var orderPersonalPropertys = new Array();

        getCustomPersonData(orderPersonalPropertys);

        //personalData.orderPersonalPropertys = orderPersonalPropertys;

        //此处进行表单验证
        for (var item in personalData.borrowers) {
            //console.log('ryy:',item)
            if (!personalData.borrowers[item].realName) {
                $(".realName").eq(item).addClass('error'); //未填写标红
                Constant.fn.Message('I', '请填写借款人' + ((parseInt(item) + 1) || ''))
                return
            }
            if (!personalData.borrowers[item].idCard) {
                $(".idCard").eq(item).addClass('error');
                Constant.fn.Message('I', '请填写身份证号码')
                return
            }

            if (!Constant.reg.isCarid.test(personalData.borrowers[item].idCard)) {
                $(".idCard").eq(item).addClass('error');
                Constant.fn.Message('I', '身份证号码格式有误！')
                return;
            }
            if (!personalData.borrowers[item].birthDate) {
                $(".birthDate").eq(item).addClass('error');
                Constant.fn.Message('I', '请填写出生日期')
                return
            }
            if (!personalData.borrowers[item].cellphone) {
                $(".cellphone").eq(item).addClass('error');
                Constant.fn.Message('I', '请填写手机号码')
                return
            }
            if (!Constant.reg.phone.test(personalData.borrowers[item].cellphone)) {
                $(".cellphone").eq(item).addClass('error');
                Constant.fn.Message('F', '手机号码格式有误')
                return
            }
            if (!personalData.borrowers[item].sex) {
                Constant.fn.Message('I', '请勾选性别')
                return
            }
        }

        if (!personalData.perInfo.residProvince) {
            $("#province_list").addClass('error');
            Constant.fn.Message('I', '请选择户口所在省')
            return
        }
        if (!personalData.perInfo.residCity) {
            $("#city_list").addClass('error');
            Constant.fn.Message('I', '请选择户口所在市')
            return
        }
        /*if (!personalData.perInfo.residArea) {
            $("#area_list").addClass('error');
            Constant.fn.Message('I', '请选择户口所在区')
            return
        }*/

        if (!personalData.perInfo.residence) {
            $("#residence").eq(item).addClass('error');
            Constant.fn.Message('I', '请填写户口所在地')
            return
        }

        if (!personalData.perInfo.addrProvince) {
            $("#rprovince_list").addClass('error');
            Constant.fn.Message('I', '请选择房产所在省')
            return
        }

        if (!personalData.perInfo.addrCity) {
            $("#rcity_list").addClass('error');
            Constant.fn.Message('I', '请选择房产所在市')
            return
        }
        /*if (!personalData.perInfo.addrArea) {
            $("#rarea_list").addClass('error');
            Constant.fn.Message('I', '请选择房产所在区')
            return
        }*/

        if (!personalData.perInfo.address) {
            $("#address").eq(item).addClass('error');
            Constant.fn.Message('I', '请填写房产地址')
            return
        }

        /*personalData.borrowers = JSON.stringify(personalData.borrowers);
        personalData.perInfo = JSON.stringify(personalData.perInfo);*/
        personalData.frontData = {
            orderPersonalPropertys: orderPersonalPropertys
        }

        //对客户信息自定义表单进行验证


        for (var i = 0; i < orderPersonalPropertys.length; i++) {
            if (orderPersonalPropertys[i].required == 1 && !orderPersonalPropertys[i].value) {
                if (orderPersonalPropertys[i].type == 'text' || orderPersonalPropertys[i].type == 'select' || orderPersonalPropertys[i].type == 'textarea') {
                    $("[id=" + orderPersonalPropertys[i].property_id + "][leipiplugins]").addClass('error')
                }
                Constant.fn.Message('I', '请填写' + $("[id=" + orderPersonalPropertys[i].property_id + "] [leipiplugins]").attr("name"));
                return false
            }
        }


        //視圖切換
        $('#apply-PersonMess').hide();
        $('a[data-type="PersonMess"]').removeClass('activePublic');
        $('#apply-message').show();
        $('a[data-type="message"]').addClass('activePublic');

        var repayment_way = $("#repanymentWay_content option:selected").data('id');
        var at_id = $("#applyTerm_content option:selected").data('id');
        var loandays = $("#apply_day").val();
        var lt_id = $("#loanType_content option:selected").data('id');
        var os_id = $("#orderSource_content option:selected").data('id');
        var feeInfos = new Array();
        var interest = $("#count span input[type='text']").val();
        var loan_way = $("#loanMethod_content input[type='radio']:checked").val();

        var feeInfos = new Array();

        var e = $("#count i[fee_id] input[type='checkbox']").parent('label');

        $.each(e, function (i, ee) {
            //分、 元
            var obj = {
                fee_id: $(ee).attr('id'),
                //order_fee_id:$(e).attr('order_fee_id'),
                fee: $(ee).siblings('label').find('input[type="text"]').val(),
                //fee_name:$(ee).text()
            }
            if ($(ee).attr('order_fee_id')) {
                obj.order_fee_id = $(ee).attr('order_fee_id')
            }

            if (!$(ee).siblings('label').find('input[type="text"]').val()) {
                obj.fee = 0;
            }

            feeInfos.push(obj)
        })

        var apply_money = parseInt(Constant.fn.toNum($('#apply_money').val()));

        var orderProductPropertys = new Array();

        getCustomProductData(orderProductPropertys);

        var data = {
            order_id: order_id,
            loan_number: $('.public-content-Po').html(),
            loan_way: loan_way,
            product_id: product_id,
            apply_money: apply_money,
            lt_id: lt_id,
            repayment_way: repayment_way,
            interest: interest,
            orderProductPropertys: orderProductPropertys,
            feeInfos: feeInfos,
            os_id: os_id,
            personalInfos: personalData
        };

        if (data.repayment_way == '4') {
            data.loandays = loandays;
        } else {
            data.at_id = at_id;
        }

        //表单验证
        for (var item in data) {
            //console.log('ryy:',item)
            if (!data.lt_id) {
                $("#loanType_content").eq(item).addClass('error'); //未填写标红
                Constant.fn.Message('I', '请选择贷款类型')
                return
            }
            if (!data.repayment_way) {
                $("#repanymentWay_content").eq(item).addClass('error');
                Constant.fn.Message('I', '请选择还款方式')
                return
            }
            if (!data.apply_money) {
                $("#apply_money").eq(item).addClass('error');
                Constant.fn.Message('I', '请填写申请金额')
                return
            }
            if (data.repayment_way != '4' && !data.at_id) {
                $("#applyTerm_content").eq(item).addClass('error');
                Constant.fn.Message('I', '请选择申请期限')
                return
            }

            if (data.repayment_way == '4' && !data.loandays) {
                $("#apply_day").addClass('error');
                Constant.fn.Message('I', '请填写申请天数');
                return
            }

            if (data.loandays && isNaN(data.loandays)) {
                $("#apply_day").addClass('error');
                Constant.fn.Message('I', '请填写正确的申请天数');
                return
            }

            if (data.repayment_way != '4' && !data.at_id) {
                $("#applyTerm_content").addClass('error');
                Constant.fn.Message('I', '请选择申请期限')
                return
            }

            if (!data.loan_way) {
                //$("#loanWay").addClass('error');
                Constant.fn.Message('I', '请选择贷款方式')
                return
            }
            if (!data.interest) {
                Constant.fn.Message('I', '请填写利率')
                return
            }
        }


        site.send({
            url: url.updateOrderInfoAll,
            async: false,
            data: {
                frontData: JSON.stringify(data)
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    Constant.fn.Message("T", data.msg);
                    history.go(-1);
                } else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })
    }


    function saveAdd2() {

        var personalData = getPersonalData();

        var orderPersonalPropertys = new Array();

        getCustomPersonData(orderPersonalPropertys);

        //personalData.orderPersonalPropertys = orderPersonalPropertys;

        //此处进行表单验证
        for (var item in personalData.borrowers) {
            //console.log('ryy:',item)
            if (!personalData.borrowers[item].realName) {
                $(".realName").eq(item).addClass('error'); //未填写标红
                Constant.fn.Message('I', '请填写借款人' + ((parseInt(item) + 1) || ''))
                return
            }
            if (!personalData.borrowers[item].idCard) {
                $(".idCard").eq(item).addClass('error');
                Constant.fn.Message('I', '请填写身份证号码')
                return
            }

            if (!Constant.reg.isCarid.test(personalData.borrowers[item].idCard)) {
                $(".idCard").eq(item).addClass('error');
                Constant.fn.Message('I', '身份证号码格式有误！')
                return;
            }
            if (!personalData.borrowers[item].birthDate) {
                $(".birthDate").eq(item).addClass('error');
                Constant.fn.Message('I', '请填写出生日期')
                return
            }
            if (!personalData.borrowers[item].cellphone) {
                $(".cellphone").eq(item).addClass('error');
                Constant.fn.Message('I', '请填写手机号码')
                return
            }
            if (!Constant.reg.phone.test(personalData.borrowers[item].cellphone)) {
                $(".cellphone").eq(item).addClass('error');
                Constant.fn.Message('F', '手机号码格式有误')
                return
            }
            if (!personalData.borrowers[item].sex) {
                Constant.fn.Message('I', '请勾选性别')
                return
            }
        }

        if (!personalData.perInfo.residProvince) {
            $("#province_list").addClass('error');
            Constant.fn.Message('I', '请选择户口所在省')
            return
        }
        if (!personalData.perInfo.residCity) {
            $("#city_list").addClass('error');
            Constant.fn.Message('I', '请选择户口所在市')
            return
        }
        /*if (!personalData.perInfo.residArea) {
            $("#area_list").addClass('error');
            Constant.fn.Message('I', '请选择户口所在区')
            return
        }*/
        if (!personalData.perInfo.residence) {
            $("#residence").eq(item).addClass('error');
            Constant.fn.Message('I', '请填写户口所在地')
            return
        }

        if (!personalData.perInfo.addrProvince) {
            $("#rprovince_list").addClass('error');
            Constant.fn.Message('I', '请选择房产所在省')
            return
        }

        if (!personalData.perInfo.addrCity) {
            $("#rcity_list").addClass('error');
            Constant.fn.Message('I', '请选择房产所在市')
            return
        }
        /*if (!personalData.perInfo.addrArea) {
            $("#rarea_list").addClass('error');
            Constant.fn.Message('I', '请选择房产所在区')
            return
        }*/

        if (!personalData.perInfo.address) {
            $("#address").eq(item).addClass('error');
            Constant.fn.Message('I', '请填写房产地址')
            return
        }

        /*personalData.borrowers = JSON.stringify(personalData.borrowers);
        personalData.perInfo = JSON.stringify(personalData.perInfo);*/
        personalData.frontData = {
            orderPersonalPropertys: orderPersonalPropertys
        }

        //对客户信息自定义表单进行验证


        for (var i = 0; i < orderPersonalPropertys.length; i++) {
            if (orderPersonalPropertys[i].required == 1 && !orderPersonalPropertys[i].value) {
                if (orderPersonalPropertys[i].type == 'text' || orderPersonalPropertys[i].type == 'select' || orderPersonalPropertys[i].type == 'textarea') {
                    $("[id=" + orderPersonalPropertys[i].property_id + "][leipiplugins]").addClass('error')
                }
                Constant.fn.Message('I', '请填写' + $("[id=" + orderPersonalPropertys[i].property_id + "] [leipiplugins]").attr("name"));
                return false
            }
        }


        //視圖切換
        $('#apply-PersonMess').hide();
        $('a[data-type="PersonMess"]').removeClass('activePublic');
        $('#apply-message').show();
        $('a[data-type="message"]').addClass('activePublic');

        var repayment_way = $("#repanymentWay_content option:selected").data('id');
        var at_id = $("#applyTerm_content option:selected").data('id');
        var loandays = $("#apply_day").val();
        var lt_id = $("#loanType_content option:selected").data('id');
        var os_id = $("#orderSource_content option:selected").data('id');
        var feeInfos = new Array();
        var interest = $("#count span input[type='text']").val();
        var loan_way = $("#loanMethod_content input[type='radio']:checked").val();

        var feeInfos = new Array();

        var e = $("#count i[fee_id] input[type='checkbox']").parent('label');

        $.each(e, function (i, ee) {
            //分、 元
            var obj = {
                fee_id: $(ee).attr('id'),
                //order_fee_id:$(e).attr('order_fee_id'),
                fee: $(ee).siblings('label').find('input[type="text"]').val(),
                //fee_name:$(ee).text()
            }
            if ($(ee).attr('order_fee_id')) {
                obj.order_fee_id = $(ee).attr('order_fee_id')
            }
            if (!$(ee).siblings('label').find('input[type="text"]').val()) {
                obj.fee = 0;
            }

            feeInfos.push(obj)
        })

        var apply_money = parseInt(Constant.fn.toNum($('#apply_money').val()));

        var orderProductPropertys = new Array();

        getCustomProductData(orderProductPropertys);

        var data = {
            loan_number: $('.public-content-Po').html(),
            loan_way: loan_way,
            product_id: product_id,
            apply_money: apply_money,
            lt_id: lt_id,
            repayment_way: repayment_way,
            interest: interest,
            orderProductPropertys: orderProductPropertys,
            feeInfos: feeInfos,
            os_id: os_id,
            personalInfos: personalData
        };

        if (data.repayment_way == '4') {
            data.loandays = loandays;
        } else {
            data.at_id = at_id;
        }

        //表单验证
        for (var item in data) {
            //console.log('ryy:',item)
            if (!data.lt_id) {
                $("#loanType_content").eq(item).addClass('error'); //未填写标红
                Constant.fn.Message('I', '请选择贷款类型')
                return
            }
            if (!data.repayment_way) {
                $("#repanymentWay_content").eq(item).addClass('error');
                Constant.fn.Message('I', '请选择还款方式')
                return
            }
            if (!data.apply_money) {
                $("#apply_money").eq(item).addClass('error');
                Constant.fn.Message('I', '请填写申请金额')
                return
            }
            if (data.repayment_way != '4' && !data.at_id) {
                $("#applyTerm_content").eq(item).addClass('error');
                Constant.fn.Message('I', '请选择申请期限')
                return
            }

            if (data.repayment_way == '4' && !data.loandays) {
                $("#apply_day").addClass('error');
                Constant.fn.Message('I', '请填写申请天数');
                return
            }

            if (data.loandays && isNaN(data.loandays)) {
                $("#apply_day").addClass('error');
                Constant.fn.Message('I', '请填写正确的申请天数');
                return
            }

            if (!data.loan_way) {
                //$("#loanWay").addClass('error');
                Constant.fn.Message('I', '请选择贷款方式')
                return
            }
            if (!data.interest) {
                Constant.fn.Message('I', '请填写利率')
                return
            }
        }

        site.send({
            url: url.updateOrderInfoAll,
            async: false,
            data: {
                frontData: JSON.stringify(data)
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    Constant.fn.Message('T', data.msg);
                    queryRole(order_id);
                    //queryNodeForm(order_id, node_id, product_id)
                    $('.processForm_winBox').toggle();
                } else {
                    Constant.fn.Message('F', data.msg)
                }
            }
        })
    }

    //保存订单
    $('#save').on('click', function () {
        saveAdd();
    })

    var source = $("#role_list_tpl").html()
    var template = Handlebars.compile(source)
    //提交，角色审批
    $('#submit').on('click', function () {
        saveAdd2()
    })

    /*********************order_apply_message************/


    /********************order_image_upload*************/


    /*site.send({
        url: url.selectAttachmentList,
        data: {
            typeName: '',
            oid: order_id,
            //acthId:
            nodeId: node_id,
            s_id: s_id,
        },
        callback: function (data) {
            data = JSON.parse(data)
            if (data.type == 1) {
                var source = $("#image_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = data.content
                var html = template(list)
                $('#image_list').append(html)

                //删除单张图片
                $('.delSingleAttach').unbind().on('click', function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                    var _this = this;
                    var attachId = $(this).parents('[attachId]').attr('attachId');
                    var attachName = $(this).parents('[attachId]').attr('attachName');
                    var img = $(this).parent('li').siblings('li');
                    var attachimg = new Array();
                    if (img.length) {
                        $.each(img, function (i, e) {
                                var href = $(e).attr('href');
                                attachimg.push($(e).attr('href'));
                            }
                        )
                    }
                    site.send({
                        url: url.insertAttachment,
                        data: {
                            attachImg: JSON.stringify(attachimg),
                            attachName: attachName,
                            attachId: attachId,
                            oid: order_id,
                            //oid: 1,
                            productId: product_id,
                            nodeId: node_id,
                            //nodeId: 2,
                            order_num: order_num,
                            //s_id: '1'
                        },
                        callback: function (data) {
                            data = JSON.parse(data)
                            if (data.type == 1) {
                                $(_this).parents('li').remove();
                            }
                        }
                    })
                })

                //删除整个附件
                $('.delAttach').unbind().on('click', function () {
                    var _this = this;
                    var id = $(this).parents('tr').find('[attachId]').attr('allid');
                    site.send({
                        url: url.delAttachment,
                        data: {
                            id: id
                        },
                        callback: function (data) {
                            data = JSON.parse(data);
                            if (data.type == 1) {
                                $(_this).parents('tr').remove();
                                $('[id^="gallery"]').viewer('destroy').viewer();
                            }
                            else {
                                Constant.fn.Message(data.msg);
                            }
                        }
                    })
                })

                $('[id^="gallery"]').viewer('destroy').viewer();
            }
            else {
                Constant.fn.Message("I", data.msg)
            }
        }
    })*/

    //查出已上传图片
    function selectAttachment(id) {
        var data = {
            oid: order_id,
            product_id: product_id,
        }
        if (id) {
            data.attach_id = id;
        }
        site.send({
            url: url.selectAttachmentList,
            data: data,
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    if (data.content) {
                        $('.result').html(data.content.length);
                    }
                    var source = $("#image_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data.content
                    $.each(list, function (i, e) {
                        e.img = [];
                        e.file = [];
                        if (e.attachImg && e.attachImg.length) {
                            $.each(e.attachImg, function (ii, ee) {
                                if (ee) {
                                    var postFix = Constant.fn.getFileType(ee);
                                    if (postFix === 'jpg' || postFix === 'png' || postFix === 'jpeg') {
                                        e.img.push(ee);
                                    } else {
                                        e.file.push({
                                            href: ee,
                                            type: postFix,
                                            name: Constant.fn.getFileName(ee)
                                        });
                                    }
                                } else {

                                }
                            })
                        }
                        e.imgLength = e.img.length;
                        e.fileLength = e.file.length;
                    })
                    var html = template(list)
                    $('#image_list').html(html)

                    /*if (!id) {
                        var source = $("#attachmentType_tpl").html();
                        var template = Handlebars.compile(source);
                        var list = data.content
                        var html = template(list)
                        $('#attachmentType').html(html)
                    }*/

                    //删除单张图片
                    $('.delSingleAttach').unbind().on('click', function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        var _this = this;
                        var attachId = $(this).parents('[attachId]').attr('attachId');
                        var attachName = $(this).parents('[attachId]').attr('attachName');
                        var img = $(this).parent().siblings();
                        var file = $(this).parent('[attachid]').siblings('[attachid]').children();
                        var attachimg = new Array();
                        if (img.length) {
                            $.each(img, function (i, e) {
                                    var href = $(e).attr('href');
                                    attachimg.push($(e).attr('href'));
                                }
                            )
                        }

                        if (file.length) {
                            $.each(file, function (i, e) {
                                    var href = $(e).attr('href');
                                    attachimg.push($(e).attr('href'));
                                }
                            )
                        }

                        site.send({
                            url: url.insertAttachment,
                            data: {
                                attachImg: JSON.stringify(attachimg),
                                attachName: attachName,
                                attachId: attachId,
                                oid: order_id,
                                //oid: 1,
                                productId: product_id,
                                nodeId: node_id,
                                //nodeId: 2,
                                order_num: order_num,
                                //s_id: '1'
                                is_target: attachId == '65' ? 1: -1
                            },
                            callback: function (data) {
                                data = JSON.parse(data)
                                if (data.type == 1) {
                                    $(_this).parents('li').remove();
                                }
                            }
                        })
                    })

                    //删除单个文件
                    $('.delSingleFileAttach').unbind().on('click', function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        var _this = this;
                        var attachId = $(this).parents('[attachId]').attr('attachId');
                        var attachName = $(this).parents('[attachId]').attr('attachName');
                        var file = $(this).parent('a').siblings('a');
                        var img = $(this).parent('tr').find('[id*=gallery]').find('li');

                        var data = {
                            attachImg: "",
                            attachName: attachName,
                            attachId: attachId,
                            oid: order_id,
                            productId: product_id,
                            nodeId: node_id,
                            order_num: order_num
                        }

                        if(attachId == '65'){
                            data.is_target = 1;
                        }else{
                            data.is_target = -1;
                        }

                        var attachimg = new Array();

                        if (file.length) {
                            $.each(file, function (i, e) {
                                    var href = $(e).attr('href');
                                    attachimg.push($(e).attr('href'));
                                }
                            )
                        }

                        if (img.length) {
                            $.each(img, function (i, e) {
                                    var href = $(e).attr('href');
                                    attachimg.push($(e).attr('href'));
                                }
                            )
                        }

                        if (attachimg.length) {
                            data.attachImg = JSON.stringify(attachimg)
                        }
                        site.send({
                            url: url.insertAttachment,
                            data: data,
                            callback: function (data) {
                                data = JSON.parse(data)
                                if (data.type == 1) {
                                    if ($(_this).parents('td').find('a').length < '1' && $(_this).parents('td').find('li').length < '1') {
                                        site.send({
                                            url: url.delAttachment,
                                            data: {
                                                id: $(_this).parents('tr').find('[attachId]').attr('allid')
                                            },
                                            callback: function (data) {
                                                data = JSON.parse(data);
                                                if (data.type == 1) {
                                                    $(_this).parents('tr').remove();
                                                    $('[id^="gallery"]').viewer('destroy').viewer();
                                                }
                                                else {
                                                    Constant.fn.Message('F', data.msg);
                                                }
                                            }
                                        })
                                    }
                                    else {
                                        $(_this).parents('a').remove();
                                    }
                                }
                            }
                        })
                    })


                    //删除整个附件
                    $('.delAttach').unbind().on('click', function () {
                        var _this = this;
                        var id = $(this).parents('tr').find('[attachId]').attr('allid');
                        site.send({
                            url: url.delAttachment,
                            data: {
                                id: id
                            },
                            callback: function (data) {
                                data = JSON.parse(data);
                                if (data.type == 1) {
                                    $(_this).parents('tr').remove();
                                    $('[id^="gallery"]').viewer('destroy').viewer();
                                }
                                else {
                                    Constant.fn.Message(data.msg);
                                }
                            }
                        })
                    })

                    $('[id^="gallery"]').viewer('destroy').viewer();

                    $(".more").on('click', function () {
                        if ($(this).data('rotate') % 2 === 0) {
                            $(this).css('transform', 'rotate(180deg)');
                        } else {
                            $(this).css('transform', 'rotate(0deg)');
                        }
                        $(this).data('rotate', $(this).data('rotate') + 1);
                        $(this).parents('[id^="gallery"]').find('li:gt(2)').toggle();
                    })
                    $(".fileMore").on('click', function () {
                        if ($(this).data('rotate') % 2 === 0) {
                            $(this).css('transform', 'rotate(180deg)');
                        } else {
                            $(this).css('transform', 'rotate(0deg)');
                        }
                        $(this).data('rotate', $(this).data('rotate') + 1);
                        $(this).parents('[id^="fileGallery"]').find('a:gt(2)').toggle();
                    })
                }
                else {
                    Constant.fn.Message("I", data.msg)
                }
            }
        })
    }

    selectAttachment();

    /*$(".icon-sousuo").on('click', function () {
        selectAttachment($("#attachmentType").val())
    })*/

    // WebUploader实例
    var uploader;
    var urlheader = {
        insertAttachment: "manager/insertAttachment.do"
    }

    var attachId, attachName, order_num;

    function OSS_IMAGE_INIT(order_id, node_id) {

        var objdata = {
            upfile_nametype: 'random_name',//local_name random_name  上传文件的文件名类型
            url: localStorage.getItem('host') + "oss/getSignature.do"
        };
        // 当domReady的时候开始初始化
        $("#viewPic").on('click', function () {
            order_num = $('.public-content-Po').html();

            timeout : 30000,
                $.ajax({
                    type: "post",
                    url: objdata.url,
                    success: function (str) {
                        data = JSON.parse(str)
                        if (data.type > 0) {
                            try {
                                var re = data.content;
                                objdata.osssignature = {
                                    'key': re.dir,
                                    'policy': re.policy,
                                    'OSSAccessKeyId': re.accessId,
                                    'success_action_status': '200', //让服务端返回200,不然，默认会返回204
                                    'signature': re.signature,
                                    'callback': re.callback,
                                    'expire': re.expire,
                                    'host': re.host
                                };
                            } catch (e) {
                                Constant.fn.Message('F', "系统错误");
                            }

                        } else {
                            Constant.fn.Message("F", "结果为空");
                        }
                        $("#image_upload_pop").toggle();

                        //设置居中
                        centerPosition($("#image_upload_pop .edui-dialog-body").get(0));
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        // Constant.fn.Message("ajax error");
                    },
                    complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
                        if (status == 'timeout') {
                            //Constant.fn.Message('请求超时，请稍后再试！');
                        }
                    },
                    async: false
                });

            if (uploader) return;//界面已经存在，不去重新创建uploader了

            var $wrap = $('#uploader'),
                // 图片容器
                $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList')),

                // 状态栏，包括进度和控制按钮
                $statusBar = $wrap.find('.statusBar'),

                // 文件总体选择信息。
                $info = $statusBar.find('.info'),

                // 上传按钮
                $upload = $wrap.find('.uploadBtn'),

                // 没选择文件之前的内容。
                $placeHolder = $wrap.find('.placeholder'),

                $progress = $statusBar.find('.progress').hide(),

                // 添加的文件数量
                fileCount = 0,

                // 添加的文件总大小
                fileSize = 0,

                acceptExtensions = [".png", ".tif", ".TIF", ".pdf", ".doc", ".docx", ".jpg", ".jpeg", ".gif", ".bmp", ".xls", ".xlsx"].join('').replace(/\./g, ',').replace(/^[,]/, ''),

                // 优化retina, 在retina下这个值是2
                ratio = window.devicePixelRatio || 1,

                // 缩略图大小
                thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio,

                // 可能有pedding, ready, uploading, confirm, done.
                state = 'pedding',

                // 所有文件的进度信息，key为file id
                percentages = {},
                // 判断浏览器是否支持图片的base64
                isSupportBase64 = (function () {
                    var data = new Image();
                    var support = true;
                    data.onload = data.onerror = function () {
                        if (this.width != 1 || this.height != 1) {
                            support = false;
                        }
                    }
                    data.src = "";
                    return support;
                })(),

                // 检测是否已经安装flash，检测flash的版本
                flashVersion = (function () {
                    var version;

                    try {
                        version = navigator.plugins['Shockwave Flash'];
                        version = version.description;
                    } catch (ex) {
                        try {
                            version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
                        } catch (ex2) {
                            version = '0.0';
                        }
                    }
                    version = version.match(/\d+/g);
                    return parseFloat(version[0] + '.' + version[1], 10);
                })(),

                supportTransition = (function () {
                    var s = document.createElement('p').style,
                        r = 'transition' in s || 'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s;
                    s = null;
                    return r;
                })(), _this = this;

            _this.imageList = [];
            if (!WebUploader.Uploader.support('flash') /* && WebUploader.browser.ie */) {

                // flash 安装了但是版本过低。
                if (flashVersion) {
                    (function (container) {
                        window['expressinstallcallback'] = function (state) {
                            switch (state) {
                                case 'Download.Cancelled':
                                    Constant.fn.Message('您取消了更新！')
                                    break;

                                case 'Download.Failed':
                                    Constant.fn.Message('安装失败')
                                    break;

                                default:
                                    Constant.fn.Message('安装已成功，请刷新！');
                                    break;
                            }
                            delete window['expressinstallcallback'];
                        };

                        var swf = './expressInstall.swf';
                        // insert flash object
                        var html = '<object type="application/' + 'x-shockwave-flash" data="' + swf + '" ';

                        if (WebUploader.browser.ie) {
                            html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
                        }

                        html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + swf + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>';

                        container.html(html);

                    })($wrap);

                    // 压根就没有安装。
                } else {
                    $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
                }

                return;
            } else if (!WebUploader.Uploader.support()) {
                Constant.fn.Message('Web Uploader 不支持您的浏览器！');
                return;
            }
            // 实例化
            uploader = WebUploader.create({
                pick: {
                    id: '#filePicker',
                    label: '点击选择图片'
                },
                resize: false,
                duplicate: true,
                fileSizeLimit: 2048,
                accept: {
                    title: 'Images',
                    extensions: acceptExtensions,
                    // mimeTypes: 'filed/!*' //wuzhifeng 修改上传文件类型 图片的话 是
                    // image
                    mimeTypes: 'image/!*'
                },
                formData: {
                    uid: 123
                },
                dnd: '#edui114_body',
                paste: '#uploader',
                swf: '/tbpt/plugin/ueditor/third-party/webuploader/Uploader.swf',
                chunked: false,
                compress: false,
                chunkSize: 512 * 1024,
                server: objdata.osssignature.host,//tbpt/plugin/ueditor/jsp/controller.jsp?action=uploadimage
                //http://oss.aliyuncs.com/ http://tbptfile.oss-cn-beijing.aliyuncs.com/
                // runtimeOrder: 'flash',
                // 'http://liaoxuezhi.fe.baidu.com/webupload/fileupload.php',
                // server: 'http://www.2betop.net/fileupload.php',
                // accept: {
                // title: 'Images',
                // extensions: 'gif,jpg,jpeg,bmp,png',
                // mimeTypes: 'image/!*'
                // },
                // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
                disableGlobalDnd: false,
                auto: false,// {Boolean} [可选] [默认值：false] 设置为 true
                // 后，不需要手动调用上传，有文件选择即开始上传。
                fileNumLimit: 300,// 验证文件总数量, 超出则不允许加入队列。
                fileSizeLimit: 200 * 1024 * 1024, // 200 M
                fileSingleSizeLimit: 110 * 1024 * 1024 // 50 M
            });

            // 拖拽时不接受 js, txt 文件。
            uploader.on('dndAccept', function (items) {
                var denied = false, len = items.length, i = 0,
                    // 修改js类型
                    unAllowed = 'text/plain;application/javascript ';

                for (; i < len; i++) {
                    // 如果在列表里面
                    if (~unAllowed.indexOf(items[i].type)) {
                        denied = true;
                        break;
                    }
                }

                return !denied;
            });
            // 添加“添加文件”的按钮，
            uploader.addButton({
                id: '#filePicker2',
                label: '继续添加'
            });

            uploader.on('ready', function () {
                window.uploader = uploader;
            });

            //上传完成 服务器响应 不代表上传成功
            uploader.on('uploadSuccess', function (file, ret) {
                //console.log(fileCount);
                var $file = $('#' + file.id);
                if (ret._raw) {
                    _this.imageList.push({
                        succ: true
                    });
                    $file.append('<span class="success"></span>');
                    //图片
                    if (file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/tiff') {
                        //console.log($file.index());
                        var index = $file.index();
                        /*if ($file.index() == 0) {
                            $('#picStay').prepend('原图:<a sort="' + $file.index() + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            $('#picStay').prepend('<img sort="' + $file.index() + '" src="' + objdata.osssignature.host + "/" + file.path + '?x-oss-process=image/resize,m_lfit,h_56,w_36" />');
                        } else {*/
                        var aSortArr = [];
                        if (!$('#picStay a').length) {
                            $('#picStay').prepend('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                        } else {
                            $.each($('#picStay a'), function (i, e) {
                                if ($(e).attr('sort') < index) {
                                    aSortArr.push($(e).attr('sort'))
                                }
                            })

                            if (aSortArr.length) {
                                $("#picStay a").eq(aSortArr.length - 1).after('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            }
                            else {
                                $('#picStay').prepend('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            }
                        }


                        var imgSortArr = [];
                        if (!$('#picStay img').length) {
                            $('#picStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" />');
                        } else {
                            $.each($('#picStay img'), function (i, e) {
                                if ($(e).attr('sort') < index) {
                                    imgSortArr.push($(e).attr('sort'))
                                }
                            })

                            if (imgSortArr.length) {
                                $("#picStay img").eq(imgSortArr.length - 1).after('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" />');
                            } else {
                                $('#picStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" />');
                            }
                        }


                        /*}*/
                        //$('#picStay').append('<img src="' + objdata.osssignature.host + "/" + file.path + '?x-oss-process=image/resize,m_fill,h_100,w_100" />');
                    }
                    else {
                        var index = $file.index();
                        /*if ($file.index() == 0) {
                            $('#picStay').prepend('原图:<a sort="' + $file.index() + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            $('#picStay').prepend('<img sort="' + $file.index() + '" src="' + objdata.osssignature.host + "/" + file.path + '?x-oss-process=image/resize,m_lfit,h_56,w_36" />');
                        } else {*/
                        var aFileSortArr = [];
                        if (!$('#fileStay a').length) {
                            $('#fileStay').prepend('原图:<a sort="' + index + '" type="' + file.type + '" name="' + file.name + '" playHref="' + objdata.osssignature.host + "/" + file.path + '" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                        } else {
                            $.each($('#fileStay a'), function (i, e) {
                                if ($(e).attr('sort') < index) {
                                    aFileSortArr.push($(e).attr('sort'))
                                }
                            })

                            if (aFileSortArr.length) {
                                $("#fileStay a").eq(aFileSortArr.length - 1).after('原图:<a sort="' + index + '" type="' + file.type + '" name="' + file.name + '" playHref="' + objdata.osssignature.host + "/" + file.path + '" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            }
                            else {
                                $('#fileStay').prepend('原图:<a sort="' + index + '" type="' + file.type + '" name="' + file.name + '" playHref="' + objdata.osssignature.host + "/" + file.path + '" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            }
                        }

                        var fileSortArr = [];
                        if (!$('#fileStay img').length) {
                            $('#fileStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '" />');
                        } else {
                            $.each($('#fileStay img'), function (i, e) {
                                if ($(e).attr('sort') < index) {
                                    fileSortArr.push($(e).attr('sort'))
                                }
                            })

                            if (fileSortArr.length) {
                                $("#fileStay img").eq(fileSortArr.length - 1).after('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '" />');
                            } else {
                                $('#fileStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '" />');
                            }
                        }
                    }
                } else {
                    showError(file.statusText);
                    $file.find('.error').text("失败").show();
                    console.log("上传失败");
                    $('body').append("上传失败");
                }

            });

            uploader.on('uploadBeforeSend', function (obj, data, headers) {
                //TODO   如果同一个页面上传多次  需要处理签名逻辑   不用每次都签名
                //debugger
                //赋值参数
                data = $.extend(data, objdata.osssignature);
                headers['Access-Control-Allow-Origin'] = "*";

                //设置文件路径
                data.key = data.key + "/" + calculate_object_name(data.name, objdata.upfile_nametype);
                obj.filepath = data.key;
                obj.file.path = data.key;
            });

            //得到文件名 type local_name random_name
            function calculate_object_name(filename, type) {
                if (type && type == 'local_name') {
                    return "${filename}";
                } else {//随机生成文件名
                    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
                    var maxPos = chars.length;
                    var random_string = '';
                    for (i = 0; i < 10; i++) {
                        random_string += chars.charAt(Math.floor(Math.random() * maxPos));
                    }
                    var pos = filename.lastIndexOf('.')
                    var suffix = ''
                    if (pos != -1) {
                        suffix = filename.substring(pos);
                    }
                    return random_string + new Date().getTime() + suffix;
                }
            }

            // 当有文件添加进来时执行，负责view的创建
            function addFile(file) {
                var $li = $('<li id="' + file.id + '">' + '<p class="title">' + file.name + '</p>' + '<p class="imgWrap"></p>' + '<p class="progress"><span></span></p>' + '</li>'),

                    $btns = $('<div class="file-panel">' + '<span class="cancel">删除</span>' + '<span class="rotateRight">向右旋转</span>' + '<span class="rotateLeft">向左旋转</span></div>').appendTo($li),
                    $prgress = $li.find('p.progress span'), $wrap = $li.find('p.imgWrap'),
                    $info = $('<p class="error"></p>'),

                    showError = function (code) {
                        switch (code) {
                            case 'exceed_size':
                                text = '文件大小超出';
                                break;

                            case 'interrupt':
                                text = '上传暂停';
                                break;

                            default:
                                text = '上传失败，请重试';
                                break;
                        }

                        $info.text(text).appendTo($li);
                    };

                if (file.getStatus() === 'invalid') {
                    showError(file.statusText);
                } else {
                    // @todo lazyload
                    $wrap.text('预览中');
                    uploader.makeThumb(file, function (error, src) {
                        var img;

                        if (error) {
                            $wrap.text('不能预览');
                            return;
                        }

                        if (isSupportBase64) {
                            img = $('<img src="' + src + '">');
                            $wrap.empty().append(img);
                        }
                    }, thumbnailWidth, thumbnailHeight);

                    percentages[file.id] = [file.size, 0];
                    file.rotation = 0;
                }


                file.on('statuschange', function (cur, prev) {
                    if (prev === 'progress') {
                        $prgress.hide().width(0);
                    } else if (prev === 'queued') {
                        $li.off('mouseenter mouseleave');
                        $btns.remove();
                    }
                    // 成功
                    if (cur === 'error' || cur === 'invalid') {
                        console.log(file.statusText);
                        showError(file.statusText);
                        percentages[file.id][1] = 1;
                    } else if (cur === 'interrupt') {
                        showError('interrupt');
                    } else if (cur === 'queued') {
                        percentages[file.id][1] = 0;
                    } else if (cur === 'progress') {
                        $info.remove();
                        $prgress.css('display', 'block');
                    } else if (cur === 'complete') {
                        //$li.append('<span class="success"></span>');
                    }

                    $li.removeClass('state-' + prev).addClass('state-' + cur);
                });
                uploader.on('uploadAccept', function (file, response) {
                    var hasError = (response['error'] !== undefined);
                    if (hasError) {
                        // 通过return false来告诉组件，此文件上传有错。
                        return false;
                    }
                    ;
                });
                uploader.on("uploadFinished", function () {
                    // uploader.reset();
                    // uploader;
                });

                $li.on('mouseenter', function () {
                    $btns.stop().animate({
                        height: 30
                    });
                });

                $li.on('mouseleave', function () {
                    $btns.stop().animate({
                        height: 0
                    });
                });

                $btns.on('click', 'span', function () {
                    var index = $(this).index(), deg;

                    switch (index) {
                        case 0:
                            uploader.removeFile(file);
                            return;

                        case 1:
                            file.rotation += 90;
                            break;

                        case 2:
                            file.rotation -= 90;
                            break;
                    }

                    if (supportTransition) {
                        deg = 'rotate(' + file.rotation + 'deg)';
                        $wrap.css({
                            '-webkit-transform': deg,
                            '-mos-transform': deg,
                            '-o-transform': deg,
                            'transform': deg
                        });
                    } else {
                        $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
                    }

                });

                $li.appendTo($queue);
            }

            // 负责view的销毁
            function removeFile(file) {
                var $li = $('#' + file.id);

                delete percentages[file.id];
                updateTotalProgress();
                $li.off().find('.file-panel').off().end().remove();
            }

            function updateTotalProgress() {
                var loaded = 0, total = 0, spans = $progress.children(), percent;

                $.each(percentages, function (k, v) {
                    total += v[0];
                    loaded += v[0] * v[1];
                });

                percent = total ? loaded / total : 0;

                spans.eq(0).text(Math.round(percent * 100) + '%');
                spans.eq(1).css('width', Math.round(percent * 100) + '%');
                updateStatus();
            }

            function updateStatus() {
                var text = '', stats;

                if (state === 'ready') {
                    text = '选中' + fileCount + '张图片，共' + WebUploader.formatSize(fileSize) + '。';
                } else if (state === 'confirm') {
                    stats = uploader.getStats();
                    if (stats.uploadFailNum) {
                        text = '已成功上传' + stats.successNum + '张照片，' + stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
                    }

                } else {
                    stats = uploader.getStats();
                    text = '共' + fileCount + '张（' + WebUploader.formatSize(fileSize) + '），已上传' + stats.successNum + '张';

                    if (stats.uploadFailNum) {
                        text += '，失败' + stats.uploadFailNum + '张';
                    }
                }

                $info.html(text);
            }

            function setState(val) {
                var file, stats;

                if (val === state) {
                    return;
                }

                $upload.removeClass('state-' + state);
                $upload.addClass('state-' + val);
                state = val;

                switch (state) {
                    case 'pedding':
                        $placeHolder.removeClass('element-invisible');
                        $queue.hide();
                        $statusBar.addClass('element-invisible');
                        uploader.refresh();
                        break;

                    case 'ready':
                        $placeHolder.addClass('element-invisible');
                        $('#filePicker2').removeClass('element-invisible');
                        $queue.show();
                        $statusBar.removeClass('element-invisible');
                        uploader.refresh();
                        $upload.text('开始上传').removeClass('disabled');
                        break;

                    case 'uploading':
                        $('#filePicker2').addClass('element-invisible');
                        $progress.show();
                        $upload.text('暂停上传');
                        break;

                    case 'paused':
                        $progress.show();
                        $upload.text('继续上传');
                        break;

                    case 'confirm':
                        $progress.hide();
                        $upload.text('开始上传').addClass('disabled');

                        stats = uploader.getStats();
                        if (stats.successNum && !stats.uploadFailNum) {
                            setState('finish');
                            return;
                        }
                        break;
                    case 'finish':
                        stats = uploader.getStats();
                        if (stats.successNum) {

                            // WuZhiFeng

                        } else {
                            // 没有成功的图片，重设
                            state = 'done';
                            location.reload();
                        }
                        $('#filePicker2').removeClass('element-invisible');
                        $upload.text('开始上传').removeClass('disabled');
                        break;
                }

                updateStatus();
            }

            uploader.onUploadProgress = function (file, percentage) {
                var $li = $('#' + file.id), $percent = $li.find('.progress span');

                $percent.css('width', percentage * 100 + '%');
                if ($.isEmptyObject(percentages)) {
                    return false;
                }
                percentages[file.id][1] = percentage;
                updateTotalProgress();
            };

            uploader.onFileQueued = function (file) {
                fileCount++;
                fileSize += file.size;

                if (fileCount === 1) {
                    $placeHolder.addClass('element-invisible');
                    $statusBar.show();
                }

                addFile(file);
                setState('ready');
                updateTotalProgress();
            };

            uploader.onFileDequeued = function (file) {
                fileCount--;
                fileSize -= file.size;

                if (!fileCount) {
                    setState('pedding');
                }

                removeFile(file);
                updateTotalProgress();

            };

            uploader.on('all', function (type) {
                var stats;
                switch (type) {
                    case 'uploadFinished':
                        setState('confirm');
                        break;

                    case 'startUpload':
                        setState('uploading');
                        break;

                    case 'stopUpload':
                        setState('paused');
                        break;

                }

            });

            uploader.onError = function (code) {
                if (code == 'Q_TYPE_DENIED') {
                    Constant.fn.Message("不支持该文件类型，请选择图片类型文件");
                }
                if (code == 'Q_EXCEED_NUM_LIMIT') {
                    Constant.fn.Message("只能上传单张图片");
                }
                // Constant.fn.Message( 'Eroor: ' + code );
            };

            $upload.on('click', function () {
                if ($(this).hasClass('disabled')) {
                    return false;
                }

                if (state === 'ready') {
                    uploader.upload();
                } else if (state === 'paused') {
                    uploader.upload();
                } else if (state === 'uploading') {
                    uploader.stop();
                }
            });

            $info.on('click', '.retry', function () {
                uploader.retry();
            });

            $info.on('click', '.ignore', function () {
                Constant.fn.Message('todo');
            });

            $upload.addClass('state-' + state);
            updateTotalProgress();


        });

    }

    var resetUploader = function () {
        if (uploader) {
            //重新设置页面
            for (var i = 0; i < uploader.getFiles().length; i++) {
                uploader.removeFile(uploader.getFiles()[i]);
            }
            uploader.reset();
        }
        $('.webuploader-element-invisible').val('');
    };

    $(".closed").unbind();
    $(".sure").unbind();

    $(".closed").on('click', function () {
        resetUploader();
        $('#image_upload_pop').toggle();
        $("#picStay").html("");
    })

    $(".sure").on('click', function () {
        /*var status = uploader.getStats();
        console.log(status);
        if (status.queueNum) {
            $(".statusBar .info").html("还有" + status.queueNum + "张图片未上传");
            return
        }*/
        $('#image_upload_pop').toggle();
        resetUploader();
    })

    $("#sureUpload").on('click', function () {
        var img = $("#picStay a");
        var file = $("#fileStay a");
        var attachImg = new Array();
        var attachimg = new Array();
        var attachFile = [];
        var attachfile = [];
        attachId = $("#attachmentType option:selected").data('id');
        attachName = $("#attachmentType option:selected").text();
        if (!attachId) {
            Constant.fn.Message('I', '请选择类型');
            return;
        }
        if (img.length) {
            $.each(img, function (i, e) {
                attachImg.push(
                    {
                        playHref: $(e).attr('playhref'),
                        href: $(e).attr('href'),
                        attachId: attachId,
                        name: $(e).attr('name'),
                        type: $(e).attr('type')
                    }
                );
            })

            $.each(img, function (i, e) {
                attachimg.push($(e).attr('href'))
            })

            var sameAttach = $('[attachid=' + attachId + '] li');
            if (sameAttach.length) {
                $.each(sameAttach, function (i, e) {
                    attachimg.push($(e).attr('href'))
                })
            }

            var sameAttachFile = $('[attachid=' + attachId + '] a');
            if (sameAttachFile.length) {
                $.each(sameAttachFile, function (i, e) {
                    attachimg.push($(e).attr('href'))
                })
            }

            //上传图片
            site.send({
                url: urlheader.insertAttachment,
                data: {
                    attachImg: JSON.stringify(attachimg),
                    attachName: attachName,
                    attachId: attachId,
                    oid: order_id,
                    //oid: 1,
                    productId: product_id,
                    nodeId: node_id,
                    //nodeId: 2,
                    order_num: order_num,
                    //s_id: '1'
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var flag = true;
                    if (data.type = 1) {
                        Constant.fn.Message('T', data.msg);

                        //各种情况判断
                        if (attachImg.length) {
                            if ($('[id*=gallery]').length) {
                                $.each($('[id*=gallery]'), function (i, e) {
                                    if (attachImg[0].attachId == $(e).attr('attachId')) {
                                        $.each(attachImg, function (ii, ee) {
                                            if (Constant.fn.getFileType(ee.href) == 'pdf') {
                                                $(e).append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                    '<img class="img_00" src="static/css/images/pdf.png">\n' +
                                                    '<div title='+ee.name+'>' + ee.name + '</div>\n' +
                                                    '<i class="delSingleAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</a>')
                                            }else if(Constant.fn.getFileType(ee.href) == 'xls' || Constant.fn.getFileType(ee.href) == 'xlsx'){
                                                $(e).append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                    '<img class="img_00" src="static/css/images/xls.png">\n' +
                                                    '<div title=\'+ee.name+\'>' + ee.name + '</div>\n' +
                                                    '<i class="delSingleAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</a>')
                                            }else if(Constant.fn.getFileType(ee.href) == 'docx' || Constant.fn.getFileType(ee.href) == 'doc'){
                                                $(e).append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                    '<img class="img_00" src="static/css/images/word.png">\n' +
                                                    '<div title=\'+ee.name+\'>' + ee.name + '</div>\n' +
                                                    '<i class="delSingleAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</a>')
                                            }else {
                                                $(e).append('<li href=\"' + ee.href + '\">   \n' +
                                                    '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                                    '<i class="delSingleAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</li>')
                                            }
                                        })

                                        $("#picStay").html("");
                                        flag = false;
                                    }
                                })

                                if (flag) {
                                    $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" +
                                        data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content
                                            [0].id + "></div>  <div id=\"fileGallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" +
                                        data.content[0].attachId + "\" allid=" + data.content[0].id + "></div> </td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                                    $.each(attachImg, function (ii, ee) {
                                        var gallery = $('[id*=gallery' + ee.attachId + ']');
                                        if (Constant.fn.getFileType(ee.href) == 'pdf') {
                                            gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                '<img class="img_00" src="static/css/images/pdf.png" >\n' +
                                                '<div title=\'+ee.name+\'>' + ee.name + '</div>\n' +
                                                '<i class="delSingleAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</a>')
                                        }else if(Constant.fn.getFileType(ee.href) == 'xls' || Constant.fn.getFileType(ee.href) == 'xlsx'){
                                            gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                '<img class="img_00" src="static/css/images/xls.png" >\n' +
                                                '<div title=\'+ee.name+\'>' + ee.name + '</div>\n' +
                                                '<i class="delSingleAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</a>')
                                        }else if(Constant.fn.getFileType(ee.href) == 'docx' || Constant.fn.getFileType(ee.href) == 'doc'){
                                            gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                '<img class="img_00" src="static/css/images/word.png">\n' +
                                                '<div title=\'+ee.name+\'>' + ee.name + '</div>\n' +
                                                '<i class="delSingleAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</a>')
                                        }else {
                                            gallery.append('<li href=\"' + ee.href + '\">   \n' +
                                                '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                                '<i class="delSingleAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</li>')
                                        }
                                    })

                                    //imgList(data.content[0].attachId);
                                    $("#picStay").html("");
                                }
                            }

                            else {
                                $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" +
                                    data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content
                                        [0].id + "></div>  <div id=\"fileGallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" +
                                    data.content[0].attachId + "\" allid=" + data.content[0].id + "></div> </td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                                $.each(attachImg, function (ii, ee) {
                                    var gallery = $('[id*=gallery' + ee.attachId + ']');
                                    if (Constant.fn.getFileType(ee.href) == 'pdf') {
                                        gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                            '<img class="img_00" url="static/css/images/pdf.png" src="' + type + '">\n' +
                                            '<div title=\'+ee.name+\'>' + ee.name + '</div>\n' +
                                            '<i class="delSingleAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</a>')
                                    }else if(Constant.fn.getFileType(ee.href) == 'xls' || Constant.fn.getFileType(ee.href) == 'xlsx'){
                                        gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                            '<img class="img_00" src="static/css/images/xls.png" >\n' +
                                            '<div title=\'+ee.name+\'>' + ee.name + '</div>\n' +
                                            '<i class="delSingleAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</a>')
                                    }else if(Constant.fn.getFileType(ee.href) == 'docx' || Constant.fn.getFileType(ee.href) == 'doc'){
                                        gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                            '<img class="img_00" src="static/css/images/word.png" >\n' +
                                            '<div title=\'+ee.name+\'>' + ee.name + '</div>\n' +
                                            '<i class="delSingleAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</a>')
                                    }else {
                                        gallery.append('<li href=\"' + ee.href + '\">   \n' +
                                            '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                            '<i class="delSingleAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</li>')
                                    }
                                })

                                //imgList(data.content[0].attachId);
                                $("#picStay").html("");
                            }
                        }

                        if (attachFile.length) {
                            if ($('[id*=fileGallery]').length) {
                                $.each($('[id*=fileGallery]'), function (i, e) {
                                    if (attachFile[0].attachId == $(e).attr('attachId')) {
                                        $.each(attachFile, function (ii, ee) {
                                            if (Constant.fn.getFileType(ee.href) == 'pdf') {
                                                $(e).append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                    '<img class="img_00" src="static/css/images/pdf.png">\n' +
                                                    '<div>' + ee.name + '</div>\n' +
                                                    '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</a>')
                                            }else if(Constant.fn.getFileType(ee.href) == 'xls' || Constant.fn.getFileType(ee.href) == 'xlsx'){
                                                $(e).append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                    '<img class="img_00" src="static/css/images/xls.png">\n' +
                                                    '<div>' + ee.name + '</div>\n' +
                                                    '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</a>')
                                            }else if(Constant.fn.getFileType(ee.href) == 'docx' || Constant.fn.getFileType(ee.href) == 'doc'){
                                                $(e).append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                    '<img class="img_00" src="static/css/images/word.png">\n' +
                                                    '<div>' + ee.name + '</div>\n' +
                                                    '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</a>')
                                            }else {
                                                $(e).append('<li href=\"' + ee.href + '\">   \n' +
                                                    '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                                    '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</li>')
                                            }
                                        })

                                        $("#fileStay").html("");
                                        flag = false;
                                    }
                                })

                                if (flag) {
                                    $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content[0].id + "></div></td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                                    $.each(attachFile, function (ii, ee) {
                                        var gallery = $('[id*=fileGallery' + ee.attachId + ']');
                                        if (Constant.fn.getFileType(ee.href) == 'pdf') {
                                            gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                '<img class="img_00" src="static/css/images/pdf.png" >\n' +
                                                '<div>' + ee.name + '</div>\n' +
                                                '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</a>')
                                        }else if(Constant.fn.getFileType(ee.href) == 'xls' || Constant.fn.getFileType(ee.href) == 'xlsx'){
                                            gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                '<img class="img_00" src="static/css/images/xls.png" >\n' +
                                                '<div>' + ee.name + '</div>\n' +
                                                '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</a>')
                                        }else if(Constant.fn.getFileType(ee.href) == 'docx' || Constant.fn.getFileType(ee.href) == 'doc'){
                                            gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                '<img class="img_00" src="static/css/images/word.png">\n' +
                                                '<div>' + ee.name + '</div>\n' +
                                                '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</a>')
                                        }else {
                                            gallery.append('<li href=\"' + ee.href + '\">   \n' +
                                                '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                                '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</li>')
                                        }
                                    })

                                    //imgList(data.content[0].attachId);
                                    $("#fileStay").html("");
                                }
                            }

                            else {
                                $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" +
                                    data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content
                                        [0].id + "></div>  <div id=\"fileGallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" +
                                    data.content[0].attachId + "\" allid=" + data.content[0].id + "></div> </td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                                $.each(attachFile, function (ii, ee) {
                                    var gallery = $('[id*=fileGallery' + ee.attachId + ']');
                                    if (Constant.fn.getFileType(ee.href) == 'pdf') {
                                        gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                            '<img class="img_00" url="static/css/images/pdf.png" src="' + type + '">\n' +
                                            '<div>' + ee.name + '</div>\n' +
                                            '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</a>')
                                    }else if(Constant.fn.getFileType(ee.href) == 'xls' || Constant.fn.getFileType(ee.href) == 'xlsx'){
                                        gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                            '<img class="img_00" src="static/css/images/xls.png" >\n' +
                                            '<div>' + ee.name + '</div>\n' +
                                            '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</a>')
                                    }else if(Constant.fn.getFileType(ee.href) == 'docx' || Constant.fn.getFileType(ee.href) == 'doc'){
                                        gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                            '<img class="img_00" src="static/css/images/word.png" >\n' +
                                            '<div>' + ee.name + '</div>\n' +
                                            '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</a>')
                                    }else {
                                        gallery.append('<li href=\"' + ee.href + '\">   \n' +
                                            '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                            '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</li>')
                                    }
                                })

                                //imgList(data.content[0].attachId);
                                $("#fileStay").html("");
                            }
                        }

                        //删除单张图片
                        $('.delSingleAttach').unbind().on('click', function (e) {
                            e.stopPropagation();
                            e.preventDefault();
                            var _this = this;
                            var attachId = $(this).parents('[attachId]').attr('attachId');
                            var attachName = $(this).parents('[attachId]').attr('attachName');
                            var img = $(this).parent('li').siblings('li');
                            var file = $(this).parents('td').find('[id*=fileGallery]').find('a')

                            var data = {
                                attachImg: "",
                                attachName: attachName,
                                attachId: attachId,
                                oid: order_id,
                                productId: product_id,
                                nodeId: node_id,
                                order_num: order_num
                            }

                            if(attachId == '65'){
                                data.is_target = 1;
                            }else{
                                data.is_target = -1;
                            }

                            var attachimg = new Array();
                            if (img.length) {
                                $.each(img, function (i, e) {
                                        var href = $(e).attr('href');
                                        attachimg.push($(e).attr('href'));
                                    }
                                )
                            }

                            if(file.length){
                                $.each(file, function (i, e) {
                                        var href = $(e).attr('href');
                                        attachimg.push($(e).attr('href'));
                                    }
                                )
                            }

                            if (attachimg.length) {
                                data.attachImg = JSON.stringify(attachimg)
                            }
                            site.send({
                                url: url.insertAttachment,
                                data: data,
                                callback: function (data) {
                                    data = JSON.parse(data)
                                    if (data.type == 1) {
                                        if ($(_this).parents('td').find('a').length < '1' && $(_this).parents('td').find('li').length < '1') {
                                            site.send({
                                                url: url.delAttachment,
                                                data: {
                                                    id: $(_this).parents('tr').find('[attachId]').attr('allid')
                                                },
                                                callback: function (data) {
                                                    data = JSON.parse(data);
                                                    if (data.type == 1) {
                                                        $(_this).parents('tr').remove();
                                                        $('[id^="gallery"]').viewer('destroy').viewer();
                                                    }
                                                    else {
                                                        Constant.fn.Message('F', data.msg);
                                                    }
                                                }
                                            })
                                        }
                                        else {
                                            $(_this).parents('li').remove();
                                        }
                                    }
                                }
                            })
                        })

                        //删除整个附件
                        $('.delAttach').unbind().on('click', function () {
                            var _this = this;
                            var id = $(this).parents('tr').find('[attachId]').attr('allid');
                            site.send({
                                url: url.delAttachment,
                                data: {
                                    id: id
                                },
                                callback: function (data) {
                                    data = JSON.parse(data);
                                    if (data.type == 1) {
                                        $(_this).parents('tr').remove();
                                        $('[id^="gallery"]').viewer('destroy').viewer();
                                    }
                                    else {
                                        Constant.fn.Message('F', data.msg);
                                    }
                                }
                            })
                        })

                        $('[id^="gallery"]').viewer('destroy').viewer();
                        //Constant.fn.initScroll();
                    }
                }
            })
        }

        if (file.length) {
            $.each(file, function (i, e) {
                attachFile.push(
                    {
                        playHref: $(e).attr('playhref'),
                        href: $(e).attr('href'),
                        attachId: attachId,
                        name: $(e).attr('name'),
                        type: $(e).attr('type')
                    }
                );
            })

            $.each(file, function (i, e) {
                attachfile.push($(e).attr('href'))
            })

            var sameAttach = $('[fileAttachId=' + attachId + '] li');
            if (sameAttach.length) {
                $.each(sameAttach, function (i, e) {
                    attachfile.push($(e).attr('href'))
                })
            }

            var sameAttachFile = $('[attachid=' + attachId + '] a');
            if (sameAttachFile.length) {
                $.each(sameAttachFile, function (i, e) {
                    attachfile.push($(e).attr('href'))
                })
            }

            //上传图片
            site.send({
                url: urlheader.insertAttachment,
                data: {
                    attachImg: JSON.stringify(attachfile),
                    attachName: attachName,
                    attachId: attachId,
                    oid: order_id,
                    //oid: 1,
                    productId: product_id,
                    nodeId: node_id,
                    //nodeId: 2,
                    order_num: order_num,
                    //s_id: '1'
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var flag = true;
                    if (data.type = 1) {
                        Constant.fn.Message('T', data.msg);

                        //各种情况判断
                        if (attachFile.length) {
                            if ($('[id*=fileGallery]').length) {
                                $.each($('[id*=fileGallery]'), function (i, e) {
                                    if (attachFile[0].attachId == $(e).attr('attachId')) {
                                        $.each(attachFile, function (ii, ee) {
                                            if (Constant.fn.getFileType(ee.href) == 'pdf') {
                                                $(e).append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                    '<img class="img_00" src="static/css/images/pdf.png">\n' +
                                                    '<div>' + ee.name + '</div>\n' +
                                                    '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</a>')
                                            }else if(Constant.fn.getFileType(ee.href) == 'xls' || Constant.fn.getFileType(ee.href) == 'xlsx'){
                                                $(e).append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                    '<img class="img_00" src="static/css/images/xls.png">\n' +
                                                    '<div>' + ee.name + '</div>\n' +
                                                    '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</a>')
                                            }else if(Constant.fn.getFileType(ee.href) == 'docx' || Constant.fn.getFileType(ee.href) == 'doc'){
                                                $(e).append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                    '<img class="img_00" src="static/css/images/word.png">\n' +
                                                    '<div>' + ee.name + '</div>\n' +
                                                    '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</a>')
                                            }else {
                                                $(e).append('<li href=\"' + ee.href + '\">   \n' +
                                                    '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                                    '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                    '</i>\n' +
                                                    '</li>')
                                            }
                                        })

                                        $("#fileStay").html("");
                                        flag = false;
                                    }
                                })

                                if (flag) {
                                    $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" +
                                        data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content
                                            [0].id + "></div>  <div id=\"fileGallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" +
                                        data.content[0].attachId + "\" allid=" + data.content[0].id + "></div> </td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                                    $.each(attachFile, function (ii, ee) {
                                        var gallery = $('[id*=fileGallery' + ee.attachId + ']');
                                        if (Constant.fn.getFileType(ee.href) == 'pdf') {
                                            gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                '<img class="img_00" src="static/css/images/pdf.png" >\n' +
                                                '<div>' + ee.name + '</div>\n' +
                                                '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</a>')
                                        }else if(Constant.fn.getFileType(ee.href) == 'xls' || Constant.fn.getFileType(ee.href) == 'xlsx'){
                                            gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                '<img class="img_00" src="static/css/images/xls.png" >\n' +
                                                '<div>' + ee.name + '</div>\n' +
                                                '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</a>')
                                        }else if(Constant.fn.getFileType(ee.href) == 'docx' || Constant.fn.getFileType(ee.href) == 'doc'){
                                            gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                                '<img class="img_00" src="static/css/images/word.png">\n' +
                                                '<div>' + ee.name + '</div>\n' +
                                                '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</a>')
                                        }else {
                                            gallery.append('<li href=\"' + ee.href + '\">   \n' +
                                                '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                                '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                                '</i>\n' +
                                                '</li>')
                                        }
                                    })

                                    //imgList(data.content[0].attachId);
                                    $("#fileStay").html("");
                                }
                            }

                            else {
                                $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" +
                                    data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content
                                        [0].id + "></div>  <div id=\"fileGallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" +
                                    data.content[0].attachId + "\" allid=" + data.content[0].id + "></div> </td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                                $.each(attachFile, function (ii, ee) {
                                    var gallery = $('[id*=fileGallery' + ee.attachId + ']');
                                    if (Constant.fn.getFileType(ee.href) == 'pdf') {
                                        gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                            '<img class="img_00" url="static/css/images/pdf.png" src="' + type + '">\n' +
                                            '<div>' + ee.name + '</div>\n' +
                                            '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</a>')
                                    }else if(Constant.fn.getFileType(ee.href) == 'xls' || Constant.fn.getFileType(ee.href) == 'xlsx'){
                                        gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                            '<img class="img_00" src="static/css/images/xls.png" >\n' +
                                            '<div>' + ee.name + '</div>\n' +
                                            '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</a>')
                                    }else if(Constant.fn.getFileType(ee.href) == 'docx' || Constant.fn.getFileType(ee.href) == 'doc'){
                                        gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                            '<img class="img_00" src="static/css/images/word.png" >\n' +
                                            '<div>' + ee.name + '</div>\n' +
                                            '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</a>')
                                    }else {
                                        gallery.append('<li href=\"' + ee.href + '\">   \n' +
                                            '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                            '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</li>')
                                    }
                                })

                                //imgList(data.content[0].attachId);
                                $("#fileStay").html("");
                            }
                        }
                        //删除单张图片
                        $('.delSingleFileAttach').unbind().on('click', function (e) {
                            e.stopPropagation();
                            e.preventDefault();
                            var _this = this;
                            var attachId = $(this).parents('[attachId]').attr('attachId');
                            var attachName = $(this).parents('[attachId]').attr('attachName');
                            var file = $(this).parent('a').siblings('a');
                            var img = $(this).parents('td').find('[id*=gallery]').find('li');

                            var data = {
                                attachImg: "",
                                attachName: attachName,
                                attachId: attachId,
                                oid: order_id,
                                productId: product_id,
                                nodeId: node_id,
                                order_num: order_num
                            }

                            if(attachId == '65'){
                                data.is_target = 1;
                            }else{
                                data.is_target = -1;
                            }

                            var attachimg = new Array();

                            if (file.length) {
                                $.each(file, function (i, e) {
                                        var href = $(e).attr('href');
                                        attachimg.push($(e).attr('href'));
                                    }
                                )
                            }

                            if (img.length) {
                                $.each(img, function (i, e) {
                                        var href = $(e).attr('href');
                                        attachimg.push($(e).attr('href'));
                                    }
                                )
                            }

                            if (attachimg.length) {
                                data.attachImg = JSON.stringify(attachimg)
                            }
                            site.send({
                                url: url.insertAttachment,
                                data: data,
                                callback: function (data) {
                                    data = JSON.parse(data)
                                    if (data.type == 1) {
                                        if ($(_this).parents('td').find('a').length < '1' && $(_this).parents('td').find('li').length < '1') {
                                            site.send({
                                                url: url.delAttachment,
                                                data: {
                                                    id: $(_this).parents('tr').find('[attachId]').attr('allid')
                                                },
                                                callback: function (data) {
                                                    data = JSON.parse(data);
                                                    if (data.type == 1) {
                                                        $(_this).parents('tr').remove();
                                                        $('[id^="gallery"]').viewer('destroy').viewer();
                                                    }
                                                    else {
                                                        Constant.fn.Message('F', data.msg);
                                                    }
                                                }
                                            })
                                        }
                                        else {
                                            $(_this).parents('a').remove();
                                        }
                                    }
                                }
                            })
                        })

                        //删除整个附件
                        $('.delAttach').unbind().on('click', function () {
                            var _this = this;
                            var id = $(this).parents('tr').find('[attachId]').attr('allid');
                            site.send({
                                url: url.delAttachment,
                                data: {
                                    id: id
                                },
                                callback: function (data) {
                                    data = JSON.parse(data);
                                    if (data.type == 1) {
                                        $(_this).parents('tr').remove();
                                        $('[id^="gallery"]').viewer('destroy').viewer();
                                    }
                                    else {
                                        Constant.fn.Message('F', data.msg);
                                    }
                                }
                            })
                        })

                        $('[id^="gallery"]').viewer('destroy').viewer();
                        //Constant.fn.initScroll();
                    }
                }
            })
        }

        else {
            $("#sureUpload").addClass('error'); //未填写标红
            Constant.fn.Message('I', '请上传图片')
        }
    })


    OSS_IMAGE_INIT(order_id, node_id);

    /********************order_image_upload*************/

    //$("#jq22").viewer();
})

/**
 * 从ueditor.all.js里面拷贝的拖拽方法
 */
var _onTitlebarMouseDown = function (event, el) {
    var uiUtils = baidu.editor.ui.uiUtils;
    var domUtils = baidu.editor.dom.domUtils;
    var rect;
    var me = this;
    var dialogId = el.getAttribute('id');//'image_upload_pop';

    var safeSetOffset = function (offset) {
        // var me = this;
        var el = getDom();
        var vpRect = uiUtils.getViewportRect();
        var rect = uiUtils.getClientRect(el);
        var left = offset.left;
        if (left + rect.width > vpRect.right) {
            left = vpRect.right - rect.width;
        }
        var top = offset.top;
        if (top + rect.height > vpRect.bottom) {
            top = vpRect.bottom - rect.height;
        }
        el.style.left = Math.max(left, 0) + 'px';
        el.style.top = Math.max(top, 0) + 'px';
    }
    var getDom = function (name) {
        if (!name) {
            return document.getElementById(dialogId);
        } else {
            return document.getElementById(dialogId + '_' + name);
        }
    };

    uiUtils.startDrag(event, {
        ondragstart: function () {
            rect = uiUtils.getClientRect(getDom());
            // me.getDom('contmask').style.visibility = 'visible';
            // me.dragMask.show(me.getDom().style.zIndex - 1);
        },
        ondragmove: function (x, y) {
            var left = rect.left + x;
            var top = rect.top + y;
            safeSetOffset({
                left: left,
                top: top
            });
        },
        ondragstop: function () {
            // me.getDom('contmask').style.visibility = 'hidden';
            // domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
            // me.dragMask.hide();
        }
    });

};

var centerPosition = function (el) {
    var uiUtils = baidu.editor.ui.uiUtils;
    var vpRect = uiUtils.getViewportRect();
    var rect = uiUtils.getClientRect(el);
    var left = vpRect.width / 2 - rect.width / 2;
    var top = vpRect.height / 2 - rect.height / 2;

    el.style.left = Math.max(left, 0) + 'px';
    el.style.top = Math.max(top, 0) + 'px';
};